整數中1出現的次數
思路一:迭代
class Solution {
public:
int NumberOf1Between1AndN_Solution(int n)
{
int count=0;
for(int i=1;i<=n;i++)
{
int temp=i;
while(temp>0)
{
if(temp%10==1)
{
count++;
}
temp/=10;
}
}
return count;
}
};
思路2:利用stringstream將數字轉化爲字符串
class Solution {
public:
int NumberOf1Between1AndN_Solution(int n)
{
int count=0;
for(int i=1;i<=n;i++)
{
string res;
stringstream ss;
ss<<i; //將i轉化成流ss
ss>>res;//再將流ss轉化成字符串
for(int j=0;j<res.size();j++)
{
if(res[j]=='1')
count++;
}
}
return count;
}
};