Leetcode 233 Solution

This article provides solution to leetcode question 233 (number-of-digit-one)

https://leetcode.com/problems/number-of-digit-one

Solution

class Solution {
public:
    int countDigitOne(int n) {
        int64_t base = 1;
        int cnt = 0;

        while (n >= base)
        {
            int64_t front = n / (10 * base);
            int64_t end = n % base;
            int64_t digit = (n / base) % 10;

            cnt += front * base;

            if (digit == 1)
                cnt += end + 1;
            else if (digit != 0)
                cnt += base;

            base *= 10;
        }

        return cnt;
    }
};