# 0 ms solution with C++

• I don't think it's a difficult problem. But it has so many corner cases, it's hard to solve it with very short code.

``````class Solution {
public:
int countDigitOne(int n) {
long long count = 0;
int temp = n, digit = 0, res = 0, base = 1;

//count lowest digit
digit = n % 10;
temp = getResultAfterRemovingLowestDigit(temp);
count += temp * base + (digit >= 1);
base *= 10;

//count middle digits
while(temp >= 10) {
res = n - temp * base;
digit = temp % 10;
temp = getResultAfterRemovingLowestDigit(temp);
if (digit == 0) count += temp * base;
else if (digit == 1) count += temp * base + res + 1;
else count += (temp + 1) * base;
base *= 10;
}

//count highest digit
if (temp > 0) {
res = n - temp * base;
if (temp != 1) count += base;
else count += res + 1;
}

return count;
}

int getResultAfterRemovingLowestDigit(int number) {
if (number % 10 == 0) {
return number/10;
} else {
return (number - number % 10)/10;
}
}
};``````

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.