题目
-
输入一个整数 n ,求1~n这n个整数的十进制表示中1出现的次数。
-
例如,输入12,1~12这些整数中包含1 的数字有1、10、11和12,1一共出现了5次。
-
示例 1:
输入:n = 12
输出:5 -
示例 2:
输入:n = 13
输出:6 -
leetcode链接:https://leetcode-cn.com/problems/1nzheng-shu-zhong-1chu-xian-de-ci-shu-lcof/
思路
- 只能记数学规律了:cur表示当前位的数,high表示cur左边的数,low表示cur右边的数,digit表示Math.pow(10, cur的位),一直相加
- cur = 0, res += high * digit
- cur = 1, res += high * digit + low + 1
- cur > 1, res += high * digit + digit
/**
* @param {number} n
* @return {number}
*/
var countDigitOne = function (n) {
let digit = 1
let result = 0
let high = Math.floor(n / 10)
let low = 0
let cur = n % 10
while (high || cur) {
if (cur === 0) {
result += high * digit
} else if (cur === 1) {
result += high * digit + low + 1
} else {
result += high * digit + digit
}
low += cur * digit
cur = high % 10
high = Math.floor(high / 10)
digit *= 10
}
return result
}