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

737人阅读 评论(0)

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;
}
}

0
0

* 以上用户言论只代表其个人观点，不代表CSDN网站的观点或立场
个人资料
• 访问：1191次
• 积分：42
• 等级：
• 排名：千里之外
• 原创：3篇
• 转载：1篇
• 译文：0篇
• 评论：0条
文章分类
文章存档