Skip to content

Commit

Permalink
feat: 剑指 Offer 43. 1~n 整数中 1 出现的次数
Browse files Browse the repository at this point in the history
  • Loading branch information
manyuemeiquqi committed Jul 11, 2023
1 parent 587e8bc commit f3ee0f8
Showing 1 changed file with 27 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
/**
* @param {number} n
* @return {number}
*/
const countDigitOne = function (n) {
n = `${n}`
let i = 0
let ans = 0
while (i < n.length) {
const front = +n.slice(0, i)
const end = n.slice(i + 1)
const len = end === '' ? 0 : end.length

let count
const cur = +n[i]
if (cur > 1)
count = (front + 1) * 10 ** len
else if (cur === 1)
count = front * 10 ** len + (+end) + 1
else
count = front * 10 ** len

ans += count
i++
}
return ans
}

0 comments on commit f3ee0f8

Please sign in to comment.