leetcode刷题笔记 233题 数字 1 的个数

leetcode刷题笔记 233题 数字 1 的个数

源地址:233. 数字 1 的个数

问题描述:

给定一个整数 n,计算所有小于等于 n 的非负整数中数字 1 出现的个数。

示例:

输入: 13
输出: 6
解释: 数字 1 出现在以下数字中: 1, 10, 11, 12, 13 。

object Solution {
    def countDigitOne(n: Int): Int = {
        var pos: Long = 1
        var res: Long = 0
		
        //按位计算 各可能包含当前位为1的组合个数外加当前位可用于组合的个数
        while (pos <= n) {
            val divider: Long = pos * 10
            res = res + n / divider * pos + math.min(math.max(n % divider - pos + 1, 0.toLong), pos)
            pos = divider
        }
        
        return res.toInt
    }
}
原文地址:https://www.cnblogs.com/ganshuoos/p/13855247.html