Given an integer n, count the total number of digit 1 appearing in all non-negative integers less than or equal to n.
For example:
Given n = 13,
Return 6, because digit 1 occurred in the following numbers: 1, 10, 11, 12, 13.
本以为比较难,实际写起来还可以。按位考虑出现的次数,个位,十位,百位。每位出现1的次数为高位代表的数字乘以当前位的大小,然后考虑一下边界条件,当前位小于或者正好等于1的情况。
class Solution {
public:
int countDigitOne(int n) {
if (n <= 0) {
return 0;
}
int counts = 0;
int lowUnit = 1;
int lowNum = 0;
while (n > 0) {
int highNum = n / 10;
counts += highNum * lowUnit;
if (n % 10 > 1) {
counts += lowUnit;
}
else if (n % 10 == 1) {
counts += lowNum + 1;
}
lowNum += (n % 10) * lowUnit;
n /= 10;
lowUnit *= 10;
}
return counts;
}
};