Write a method to count the number of 2s between 0 and n.
一本书的页码从自然数1 开始顺序编码直到自然数n。书的页码按照通常的习惯编排,每个页码都不含多余的前导数字0。例如,第6 页用数字6 表示,而不是06 或006 等。数字计数问题要求对给定书的总页码n,计算出书的全部页码中分别用到多少次数字0,1, 2,…,9。
下面的代码计算出用到多少次数字2.
public static int count2sR(int n) {
// base case
if (n==0) return0;
// 513 = 5*100 +13; [power = 100, first = 5, remainder =13]
int power = 1;
while(10*power<n)
power*=10;
int first = n/power;
int remainder = n%power;
// count 2s from the first digit
int nTwosFirst = 0;
if(first>2) nTwosFirst+=power;
else if (first==2) nTwosFirst += remainder+1;
// count 2s from all other digits
int nTwosOther = first* count2sR(power-1) + count2sR(remainder);
return nTwosFirst + nTwosOther;
}