程序员面试金典——18.4 2的个数
Solution1:经典通法,得牢记啊。。。
此题在《剑指offer》中出现过,里面分析的比较到位
https://blog.csdn.net/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;
}
};