問題重述:
題目:輸入一個整數n,求從1到n這n個整數的十進制表示中1出現的次數。例如輸入12,從1到12着些整數中包含1的數字有1,10,11,12,1一共出現了5次(11中有兩個1).
思路解析:
這道題的解析下面網址給出的解析非常簡單明瞭,大家可以參閱。
代碼實現:
class Solution {
public:
int NumberOf1Between1AndN_Solution(int n)
{
int cur= 0;
int high = 0;
int low = 0;
int res = 0;
for(int i =1;i<=n;i*=10)
{
cur=(n%(i*10))/i;
high=n/(i*10);
if(i==1)
low=0;
else
low =n%i;//cur爲個位
if(cur==0)
res+=high*i;
else if(cur==1)
res+=high*i+low+1;
else
res+=(high+1)*i;
}
return res;
}
};