LeetCode in Kotlin

233. Number of Digit One

Hard

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

Example 1:

Input: n = 13

Output: 6

Example 2:

Input: n = 0

Output: 0

Constraints:

Solution

class Solution {
    fun countDigitOne(n: Int): Int {
        var ans = 0
        var k = n
        var cum = 0
        var curr10 = 1
        while (k > 0) {
            val rem = k % 10
            val q = k / 10
            ans += if (rem == 0) {
                q * curr10
            } else if (rem == 1) {
                q * curr10 + cum + 1
            } else {
                (q + 1) * curr10
            }
            k = q
            cum += rem * curr10
            curr10 *= 10
        }
        return ans
    }
}
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy