输入一个整数 n ,求1~n这n个整数的十进制表示中1出现的次数。
例如,输入12,1~12这些整数中包含1 的数字有1、10、11和12,1一共出现了5次。
本题需注意:cur,digit,low,high 的定义,及其赋值时的顺序。
题目链接:力扣
class Solution {
public int countDigitOne(int n) {
//本题固定位(十进制),利用固定位循环
//当固定位为0时,计算公式是:高位值*固定位的进制数;
//当固定为为1时,计算公式是:高位*固定位+低位+1;
//当固定位大于1时,计算公式是:(高位+1)固定位
//初始化;
int cur = n%10;
int digit =1;//是进制数
int low =0;//low的定义?
int high = n/10;
int count =0;
while(high!=0 || cur!=0){//加cur!=0是遍历到最高位
if(cur == 0) count += high*digit;
else if(cur ==1) count += high *digit +low +1;
else count += (high+1)*digit;
low += cur *digit;//这里low 是以累加的形式呈现
digit =digit*10;
//cur = cur%10;
cur=high%10;
high =high/10;
}
return count;
}
}