Count of 2s:计算[0, n]中数字2出现的个数。
如果枚举每一个数然后计算每一位中2的数量,肯定会超时的,所以应该根据n中每一位的特点来计算2的数量。
设当前位的数字为curr,该位左右两边所表示的整数用left和right表示,base = 10 ^ width(right):
curr > 2,则在left从0变化到left的过程中,每次都会出现一共可以出现10 ^ width(right)个2,总共是(left + 1) * base个curr < 2,则在left从0变化到left - 1的过程中,每次都会出现``个2,总共是left * base个curr == 2,则在left从0变化到left - 1的过程中,每次都会出现10 ^ width(right)个2,总共是left * base个,再加上right + 1个
最大输入数据为10 ^ 9,会导致base溢出,所以要在计算base之前检查left决定是否退出循环。
class Solution {
public:
int numberOf2sInRange(int n) {
int left = n, curr, right = 0, cnt = 0, base = 1;
while(1){
curr = left % 10;
left /= 10;
if(curr > 2){
cnt += (left + 1) * base;
}
else if(curr < 2){
cnt += left * base;
}
else{
cnt += left * base + right + 1;
}
if(left == 0) break;
right += curr * base;
base *= 10;
}
return cnt;
}
};
364

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



