整体思路:
该位为0,该位大于1,该位等于1,分开处理
public class Solution {
public int NumberOf1Between1AndN_Solution(int n) {
int result = 0;
int m = 0;
int s = 0;
while(n!=0)
{
int a = n/10;
//b为该位上的数字
int b = n%10;
//从右至左第m位,第一个m=1,第二个m=10,以此类推
m = (m==0)?1:m*10;
if(b==0)
result = result + a*m;
else if(b>1)
result = result + (a+1)*m;
else
result = result + a*m+s+1;
//s为已经计算过的前面位的数,比如521,我计算到5这一位s=21
s = s+m*b;
n = n/10;
}
return result;
}
}