# ［分析总结：leetcode-Number of Digit One]寻找整数1到n之间所有数字中1出现的次数

leetcode原题链接：https://leetcode.com/problems/number-of-digit-one/

public int countOnes1(int n){
int count = 0;
for(int i = 0; i <= n; i++){
int cur = i;
while(cur > 0){
int tmp = (int) i%10;
if(tmp == 1) count++;
cur = cur/10;
}
}

return count;
}


//伪代码片段
if[a(q) == 0]{
ones = a(n)...a(q+1) * 10^q;
}else if[a(q) == 1]{
ones = a(n)...a(q+1) * 10^q + [a(q-1)...a(0) + 1];
}else{// a(q) >= 2 的情况
ones = [a(n)...a(q+1) + 1] * 10^q;
}

public int countOnes2(int n){
int counts = 0;
for(long factor = 1; factor <= n; factor *= 10){
int currentNum = (n / factor) % 10;
int highNum = (n/factor)/10;
int lowNum = n % factor;

switch(currentNum){
case 0:
counts += highNum * factor;
break;
case 1:
counts += highNum * factor + lowNum + 1;
break;
default:
counts += (highNum + 1) * factor;
break;
}
}
}

public int countOnes3(int n){
int counts = 0;
for(long factor = 1; factor <= n; factor *= 10){
<span style="white-space:pre">	</span>counts += ((n/factor + 8)/10) * factor + (n/factor)%10 == 1? n%factor + 1 : 0;
}
}

• 本文已收录于以下专栏：

举报原因： 您举报文章：［分析总结：leetcode-Number of Digit One]寻找整数1到n之间所有数字中1出现的次数 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)