The thirty-first question of the sword refers to the offer
The topic is as follows
Idea and code
The first two are reckless solutions (the interview must be cool)
1. String solution
class Solution {
public:
int NumberOf1Between1AndN_Solution(int n) {
int ans=0;
for(int j=1;j<=n;j++){
string temp=to_string(j);
for(int i=0;i<temp.length();i++){
if(temp[i]=='1') ans++;
}
}
return ans;
}
};
2. Numerical solution (similar to 1, except that the string is not converted)
public int NumberOf1Between1AndN_Solution(int n) {
int count=0;
for(int i=n;i>0;i--){
for(int j=i;j>0;j/=10){
if(j%10==1) count++;
}
}return count;
The j/=10 here is still very beautiful
3. Mathematical method (dream back to the college entrance examination)
Look at the code comments, you will understand
class Solution {
public:
int NumberOf1Between1AndN_Solution(int n) {
int count=0;//1的个数
int i=1;//当前位
int current=0,after=0,before=0;
while((n/i)!=0){
before=n/(i*10);//高位
current=(n/i)%10;//当前位
after=n-(n/i)*i;//低位
if(current==0){
//如果为0,由高位决定,等于高位数字*当前位数
count+=before*i;
}else if(current==1){
//如果为1,出现1的次数由高位和低位决定,高位*当前位+低位+1
count+=before*i+after+1;
}else if(current>1){
//如果大于1,出现1的次数由高位决定,(高位数字+1)*当前位数
count+=(before+1)*i;
}
//前移一位
i*=10;
}
return count;
}
};