剑指OFFER----面试题43. 1~n整数中1出现的次数

链接:https://leetcode-cn.com/problems/1nzheng-shu-zhong-1chu-xian-de-ci-shu-lcof/

 

代码:

class Solution {
public:
    int countDigitOne(int n) {
        vector<int> number;
        if (!n) return 0;
        while(n) number.push_back(n % 10), n/= 10;
        int res = 0;
        for (int i = number.size() - 1; i >= 0; --i) {
            auto left = 0, right = 0, t = 1;
            for (int j = number.size() - 1; j > i; --j) {
                left = left * 10 + number[j];
            }
            for (int j = i - 1; j >= 0; --j) {
                right = right * 10 + number[j], t *= 10;
            }
            res += left * t;
            if (number[i] == 1) res += right + 1;
            else if (number[i] > 1) res += t;
        } 
        return res;
    }
};

 

posted @ 2020-03-04 14:08  景云ⁿ  阅读(130)  评论(0编辑  收藏  举报