#Leetcode# 233. Number of Digit One

Posted 丧心病狂工科女

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了#Leetcode# 233. Number of Digit One相关的知识,希望对你有一定的参考价值。

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

 

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.

代码:

class Solution {
public:
    int countDigitOne(int n) {
        int res = 0;
        long long a = 1, b = 1;
        while (n) {
            res += (n + 8) / 10 * a + (n % 10 == 1) * b;
            b += n % 10 * a;
            a *= 10;
            n /= 10;
        }
        return res;
    }
};

  暴力超时 新的一天从被数论教做人开始

以上是关于#Leetcode# 233. Number of Digit One的主要内容,如果未能解决你的问题,请参考以下文章

leetcode 233. Number of Digit One

LeetCode 233. Number of Digit One

LeetCode-233 Number of Digit One

[LeetCode]233 Number of Digit One(数位DP)

Leetcode 233 Number of Digit One

233 Number of Digit One 数字1的个数