问题描述:
Given an integer n, count the total number of digit 1 appearing in all non-negative integers less than or equal to n.
For example:
Given n = 13,
Return 6, because digit 1 occurred in the following numbers: 1, 10, 11, 12, 13.
分析:这道题的思路是从低位到高位分别为1时,有多少种情况,然后将这些情况累加。
注意对于某一位进行考虑时,自然的将整个数分为高位和低位两部分。而对某一位而言:它只会出现三种情况,0,1或者大于1.
0:当为0的时候,肯定会向上借位。(首位不可能为0,所以肯定会有位可借)。那此时低位可以取任意值。即:(high)*10^(低位位数)
1:当为1的时候,把高位和低位拼接起来,那最多存在这么多+1个的可能。即high*base+low;
>1:当>1时,那么就会有(high+1)*10^(低位位数)
代码如下:0ms
int countDigitOne(int n) {
int base = 1;
int count = 0;
int low = 0;//低位部分
if(n<0)
return 0;
while(n!=0){
int val = n%10;
int high = n/10;
switch (val){
case 0:
count+=high*base;
break;
case 1:
count+=high*base+low+1;
break;
default:
count+=(high+1)*base;
}
low += val*base;
base*=10;
n = n/10;
}
return count;
}