Here's the explanation.

For each digit d_i:

- If d
_{i}< 1, then the number of 1s on d_{i}== factor * (d_{i+1}- 1 + 1). Note the last (+1) is for the case when d_{i+1}is 0, and the (-1) is for that d_{i}== 0 for original d_{i+1}.

Eg. For n == 703, there are in total 7 1s on the ten's digit, when the hundred's digit could be (0~6). And for each 1s on the ten's digit, it could appear 10 times when the one's digit varies from (0~9) for each ten.

- If d
_{i}== 1, then the number of 1s on d_{i}== factor * (d_{i+1}- 1 + 1) + (number below d_{i}+ 1).

Eg. For n == 713, there are in total 7 1s on the ten's digit, when the digit on the hundreds could be (0~6). And for each 1s on the ten's digit, it could appear 4 times when the one's digit varies from (0~3) for each ten.

- If d
_{i}> 1, it's similar to 1), whereas in total 8 1s could be on the ten's digit, when the hundred's digit could be (0~7). So the number of 1s on d_{i}== factor * (d_{i+1}+ 1).

Eg. For n == 723, there are in total 8 1s on the ten's digit, when the digit on the hundreds could be (0~7). And for each 1s on the ten's digit, it could appear 10 times when the one's digit varies from (0~9) for each ten.

*Things in mind:*

There are possibilities where the **count/factor might overflow**. Use long long instead of int for them.

```
class Solution {
public:
int countDigitOne(int n) {
if (n <= 0)
return 0;
long long count = 0; //It may cause integer overflow
long long factor = 1;
while (n / factor) {
int lowerNum = n - (n / factor) * factor;
int currentDigit = (n / factor) % 10;
int higherDigit = n / (factor * 10);
switch(currentDigit) {
case 0:
count += higherDigit * factor;
break;
case 1:
count += higherDigit * factor + (lowerNum + 1);
break;
default:
count += (higherDigit + 1) * factor;
}
factor *= 10;
}
return count;
}
};
```