本题为剑指offer面试题32
牛客网测试地址:https://www.nowcoder.com/questionTerminal/bd7f978302044eee894445e244c7eee6
- 时间限制:1秒 空间限制:32768K
求出1~13的整数中1出现的次数,并算出100~1300的整数中1出现的次数?为此他特别数了一下1~13中包含1的数字有1、10、11、12、13因此共出现6次,但是对于后面问题他就没辙了。ACMer希望你们帮帮他,并把问题更加普遍化,可以很快的求出任意非负整数区间中1出现的次数。
Java代码:
package go.jacob.day507;
public class Demo2 {
public int NumberOf1Between1AndN_Solution(int n) {
int totalNum = 0;
/*
* 如果n为21345,当num=100时,pre=213,in=4,post=5
* 当num=1000时,pre=21,in=3,post=45
*/
int pre, in, post;
int num = 10;
//当pre和in同时为0,跳出循环
while (n / num != 0 || n % num / (num / 10) != 0) {
pre = n / num;
in = n % num / (num / 10);
post = n % num % (num / 10);
//分类讨论:当in>1,in=1,in<1的情况
if (in > 1)
totalNum += (pre + 1) * (num / 10);
else if (in == 1) {
totalNum += pre * (num / 10) + post + 1;
} else
totalNum += pre * (num / 10);
num = num * 10;
}
return totalNum;
}
}
本文介绍了一种高效计算指定范围内整数中数字1出现次数的方法。通过具体实例解析算法思路,包括1到13及100到1300范围内的计算,并提供Java实现代码。
401

被折叠的 条评论
为什么被折叠?



