public int NumberOf1Between1AndN_Solution(int n) {
if(n<=0)
return 0;
int high=0;
int now=0;
int low=0;
int sum=0;
for(int factory=1;n/factory!=0;factory*=10)
{
high=n/(factory*10);
now=n/factory-high*10;
low=n%factory;
if(now>1)
{
sum+=(high+1)*factory;
}else if(now<1){
sum+=(high)*factory;
}else{
sum+=(high)*factory+low+1;
}
}
return sum;
if(n<=0)
return 0;
int high=0;
int now=0;
int low=0;
int sum=0;
for(int factory=1;n/factory!=0;factory*=10)
{
high=n/(factory*10);
now=n/factory-high*10;
low=n%factory;
if(now>1)
{
sum+=(high+1)*factory;
}else if(now<1){
sum+=(high)*factory;
}else{
sum+=(high)*factory+low+1;
}
}
return sum;
}
这道题目比较简单,主要是思路要对。暴力求解实在不可取,要分开讨论数字中,每一位的可能性。