借鉴了牛客 WosAlan的思路,感谢提供思路
此外要注意base要从1开始,每次*10,不要超过n。
class Solution { public: int NumberOf1Between1AndN_Solution(int n) { if(n==0){ return 0; } //从个位数开始 int base = 1; //出现0的个数 int res = 0; while(base <= n){ int cur = n/base%10; int a = n/base/10; int b = n%base; if(cur==0){ res += a*base; }else if(cur==1){ res += 1*(b+1); res += a*base; }else{ res += (a+1)*base; } base *=10; } return res; } };