输入一个整数 n ,求1~n这n个整数的十进制表示中1出现的次数。
例如,输入12,1~12这些整数中包含1 的数字有1、10、11和12,1一共出现了5次。
示例 1:
输入:n = 12
输出:5
示例 2:
输入:n = 13
输出:6
限制:
1 <= n < 2^31
思路:分为三种情况,以及高位(当前位之前的数 high)、低位(当前位之后的数 low)、当前位之分(cur )、位因子(d)。
- 当前位为0:出现1的次数就是 高位* 位因子
- 当前位为1:出现1的次数就是 高位* 位因子 + 低位 + 1
- 当前位>0:出现1的次数就是 高位* 位因子 + 位因子
class Solution {
public int countDigitOne(int n) {
//首先初始化我们的位信息
int high = n/10;
int low = 0;
int cur = n%10;
int res = 0;
int d= 1;
//循环的条件 当high==0且cur==0的时候 证明已经越位,循环结束
while(high != 0 || cur !=0){
if(cur == 0){
res += high*d;
}else if(cur == 1){
res += high*d + low +1;
}else{
res += high*d + d;
}
//更新位信息
low += cur * d;
cur = high % 10;
high = high / 10;
d = d * 10;
}
return res;
}
}