程序员面试金典——18.4 2的个数
Solution1:经典通法,得牢记啊。。。
此题在《剑指offer》中出现过,里面分析的比较到位
https://blog.youkuaiyun.com/allenlzcoder/article/details/79619671
class Count2 {
public:
int countNumberOf2s(int n) {
// write code here
int number = 2;//只要定义不同的number,该算法是通用的
if(n < 2)
return 0;
int count = 0;
int base = 1;
int round = n;
while (round > 0) {
int weight = round%10;
round /= 10;
count += round*base;
if (weight == number)
count += (n % base) + 1;
else if (weight > number)
count += base;
base *= 10;
}
return count;
}
};
计数特定数字出现次数
本文介绍了一种经典的算法,用于计算从1到n的整数中特定数字(如2)出现的次数。通过实现一个名为countNumberOf2s的函数,可以解决《剑指offer》中的相关题目。此算法具有较高的通用性和实用性。
3090

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



