233. Number of Digit One && 剑指 Offer 43. 1~n整数中1出现的次数

Problem

Given an integer n, count the total number of digit 1 appearing in all non-negative integers less than or equal to n.

Example

Input: 13
Output: 6
Explanation: Digit 1 occurred in the following numbers: 1, 10, 11, 12, 13.

Solution

统计每一位上1出现的次数。
233. Number of Digit One && 剑指 Offer 43. 1~n整数中1出现的次数_第1张图片

class Solution {
public:
    int countDigitOne(int n)
    {
        if (n <= 0) 
            return 0;
        vector<int> nums;
        while (n) 
            nums.push_back(n % 10), n /= 10;
        reverse(nums.begin(), nums.end()); //取出每一位的数字

        int res = 0;
        for (int i = 0; i < nums.size(); i ++ ) //统计每一位上1出现的次数
        {
            int d = nums[i];
            int left = 0, right = 0, p = 1;
            for (int j = 0; j < i; j ++ ) 
                left = left * 10 + nums[j];
            for (int j = i + 1; j < nums.size(); j ++ ) {
                right = right * 10 + nums[j];
                p = p * 10;
            }
            if (d == 0) res += left * p;
            else if (d == 1) res += left * p + right + 1;
            else res += (left + 1) * p;
        }
        return res;
    }
};

你可能感兴趣的:(leetcode数学,leetcode动态规划)