My C++ 0ms accepted solution


  • 1
    S

    The main idea is to count the appearance of 1 on each digit.

    Pay more attention on the last digit and it would be OK.

    class Solution {
    public:
        int countDigitOne(const int n) {
            int ret = 0;
            if (n <= 0) return ret;
            int num = n;
            int digit = 1;
            while (num) {
                int mod = num % 10;
                int cnt = num / 10;
                int add = mod > 0 ? 1 : 0;
                
                int normal_appr_cnt = cnt * digit;
                int additional_appr_cnt;
                if (mod == 1) 
                    additional_appr_cnt = add * (n % digit + 1);
                else
                    additional_appr_cnt = add * digit;
                ret += normal_appr_cnt + additional_appr_cnt;
                
                num /= 10;
                digit *= 10;
            }
            return ret;
        }
    };

Log in to reply
 

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