输入一个整数n,求从1到n这n个整数的十进制表示中1出现的次数。例如输入12,从1到12这些整数中包含1的数字有1,10,11和12,1一共出现了5次
C++
class Solution {
public:
int NumberOf1Between1AndN_Solution(int n)
{
if(n<1)
return 0;
int count=0,round=n,base=1;
while(round)
{
int weight = round % 10;
round /= 10;
count += round *base;
if(weight==1)
count += (n % base) + 1;
else if(weight>1)
count += base;
base *=10;
}
return count;
}
};
python
# -*- coding:utf-8 -*-
class Solution:
def NumberOf1Between1AndN_Solution(self, n):
# write code here
if n < 1:
return 0
round,base,count = n,1,0
while round:
weight = round % 10
round /= 10
count += round * base
if weight == 1:
count += (n % base + 1)
elif weight > 1:
count += base
base *= 10
return count
后记总结的规律,以百位数为例:出现1 的个数 = (个位1出现次数)+(十位1出现次数)+(百位1出现次数)
534 = =(53*1+1)+(5*10+10)+(0*100+100)= 214
530 = (53*1)+(5*10+10)+(0*100+100) = 213
504 = (50*1+1)+(5*10)+(0*100+100) = 201
514 = (51*1+1)+(5*10+4+1)+(0*100+100) = 207
10 = (1*1)+(0*10+0+1) = 2