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.
Hint:
- Beware of overflow.
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; } };
浙公网安备 33010602011771号