题解 | #整数中1出现的次数(从1到n整数中1出现的次数)#
整数中1出现的次数(从1到n整数中1出现的次数)
http://www.nowcoder.com/practice/bd7f978302044eee894445e244c7eee6
贴一个C++版代码
class Solution {
public:
int NumberOf1Between1AndN_Solution(int n) {
int base=1;
int res=0;
while(base<=n){
int cur=n/base%10;
int a=n/base/10;
int b=n%base;
//分三种情况讨论
if(cur==1){
res+=abase+b+1;
}else if(cur==0){
res+=abase;
}else{
res+=(a+1)base;
}
base=10;
}
return res;
}
};