Cracking the coding interview--Q20.4
Write a method to count the number of 2s between 0 and n.
当某一位的数字小于2时,那么该位出现2的次数为:更高位数字x当前位数
当某一位的数字等于2时,那么该位出现2的次数为:更高位数字x当前位数+低位数字+1
当某一位的数字大于2时,那么该位出现2的次数为:(更高位数字+1)x当前位数
http://www.cnblogs.com/EdwardLiu/p/4274497.html
Read full article from Cracking the coding interview--Q20.4
Write a method to count the number of 2s between 0 and n.
当某一位的数字小于2时,那么该位出现2的次数为:更高位数字x当前位数
当某一位的数字等于2时,那么该位出现2的次数为:更高位数字x当前位数+低位数字+1
当某一位的数字大于2时,那么该位出现2的次数为:(更高位数字+1)x当前位数
int Count2s(int n){
int count = 0;
int factor = 1;
int low = 0, cur = 0, high = 0;
while(n/factor != 0){
low = n - (n/factor) * factor;//低位数字
cur = (n/factor) % 10;//当前位数字
high = n / (factor*10);//高位数字
switch(cur){
case 0:
case 1:
count += high * factor;
break;
case 2:
count += high * factor + low + 1;
break;
default:
count += (high + 1) * factor;
break;
}
factor *= 10;
}
return count;
}
如果我们把问题一般化一下:写一个函数,计算0到n之间i出现的次数,i是1到9的数。 这里为了简化,i没有包含0,因为按以上的算法计算0出现的次数, 比如计算0到11间出现的0的次数,会把1,2,3,4…视为01,02,03,04… 从而得出错误的结果。所以0是需要单独考虑的,为了保持一致性,这里不做讨论int Countis(int n, int i){
if(i<1 || i>9) return -1;//i只能是1到9
int count = 0;
int factor = 1;
int low = 0, cur = 0, high = 0;
while(n/factor != 0){
low = n - (n/factor) * factor;//低位数字
cur = (n/factor) % 10;//当前位数字
high = n / (factor*10);//高位数字
if(cur < i)
count += high * factor;
else if(cur == i)
count += high * factor + low + 1;
else
count += (high + 1) * factor;
factor *= 10;
}
return count;
}
X. Brute forceint Count2(int n){
int count = 0;
while(n > 0){
if(n%10 == 2)
++count;
n /= 10;
}
return count;
}
int Count2s1(int n){
int count = 0;
for(int i=0; i<=n; ++i)
count += Count2(i);
return count;
}
http://www.cnblogs.com/EdwardLiu/p/4274497.html
Read full article from Cracking the coding interview--Q20.4