求从1-n的整数中间,x出现的次数
例如:n=13,x=1,求1-13(包括1和13)中1出现的次数
1、10、11、12、13一共出现6次
方法:求每一位上x出现的次数,再相加
规律:
从右往左数第i位(i从0开始),记第i位左边的数是high,第i位右边的数是low,第i位的数是cur
第i位x出现的次数为:
1、cur < x
count = high * 10^i
2、cur > x
count = high * 10^i + 10^i
3、cur = x
count = high * 10^i + low + 1
例:1-21中出现1的次数(1、10、11、12、13、14、15、16、17、18、19,21一共为13次)
用公式验证:
从右往左第0位
high=2
cur=1(=x)
low=0
count=high*10^i+low+1=2*10^0+0+1=3
从右往左第1位
high=0
cur=2(>x)
low=1
count=high*10^i+10^i=0*10^1+10^1=10
一共出现3+13次
x=1的代码实现
public int NumberOf1Between1AndN_Solution(int n) {
int count = 0;
int i = 0, high = n, low, temp, cur;
while(high != 0) {
high = n / (int)Math.pow(10, i + 1); //第i位左边的数
temp = n % (int)Math.pow(10, i + 1); //第i位右边(包括i)的数
cur = temp / (int)Math.pow(10, i); //第i位
low = temp % (int)Math.pow(10, i); //第i位右边的数
count += high * (int)Math.pow(10, i);//基础数
//System.out.println(temp + " " + high + " " + cur + " " + low + " " + count);
if(cur > 1) {
count += (int)Math.pow(10, i);
}else if(cur == 1) {
count += low + 1;
}
i++;
}
return count;
}