- 题目描述
输入一个整数 n ,求1~n这n个整数的十进制表示中1出现的次数。
例如,输入12,1~12这些整数中包含1 的数字有1、10、11和12,1一共出现了5次。
示例 1:
输入:n = 12
输出:5
示例 2:
输入:n = 13
输出:6
限制:
1 <= n < 2^31
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/1nzheng-shu-zhong-1chu-xian-de-ci-shu-lcof
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
-
思路
1、对数字n,求出其每一位中1可能出现的次数,相加。具体请看LeetCode中该题题解 -
代码
package main
import (
"fmt"
"math"
"strconv"
)
func countDigitOne(n int) int {
str := strconv.Itoa(n)
len := len(str)
res := 0
for i := len-1; i>=0; i-- {
cur,_ := strconv.Atoi(string(str[i]))
height,_ := strconv.Atoi(string(str[:i]))
low,_ := strconv.Atoi(string(str[i+1:]))
if cur > 1 {
res += (height+1) * int(math.Pow10(len-i-1))
}
if cur == 0 {
res += height * int(math.Pow10(len-i-1))
}
if cur == 1 {
res += height * int(math.Pow10(len-i-1)) + low + 1
}
}
return res
}
func main() {
res := countDigitOne(11)
fmt.Println(res)
}