《剑指offer》面试题43. 1~n整数中1出现的次数

问题描述

输入一个整数 n ,求1~n这n个整数的十进制表示中1出现的次数。
例如,输入12,1~12这些整数中包含1 的数字有1、10、11和12,1一共出现了5次。
示例 1:

输入:n = 12
输出:5
示例 2:

输入:n = 13
输出:6
 

限制:

1 <= n < 2^31

代码

class Solution {
public:
    int countDigitOne(int n) {
        long ans = 0, div = 1, x;
        while( n >= div)
        {
            ans += n/(div*10)*div;
            x = n/div%10;
            if(x == 1)ans += n%div+1;
            else if(x > 1) ans += div;
            div *= 10;
        }
        return ans;
    }
};

结果

执行用时 :0 ms, 在所有 C++ 提交中击败了100.00%的用户
内存消耗 :5.9 MB, 在所有 C++ 提交中击败了100.00%的用户

问题和leetcode 233. 数字 1 的个数一样。

posted @ 2020-05-03 08:10  曲径通霄  阅读(103)  评论(0编辑  收藏  举报