[劍指 offer] --數學--面試題43. 1~n整數中1出現的次數

1 題目描述

輸入一個整數 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
著作權歸領釦網絡所有。商業轉載請聯繫官方授權,非商業轉載請註明出處。

2 解題思路

沒有思路的題。。。解法來自題解大佬Krahets,題解鏈接:面試題43. 1~n 整數中 1 出現的次數(清晰圖解)

在這裏插入圖片描述
在這裏插入圖片描述
在這裏插入圖片描述
在這裏插入圖片描述

在這裏插入圖片描述

作者:jyd
鏈接:https://leetcode-cn.com/problems/1nzheng-shu-zhong-1chu-xian-de-ci-shu-lcof/solution/mian-shi-ti-43-1n-zheng-shu-zhong-1-chu-xian-de-2/
來源:力扣(LeetCode)
著作權歸作者所有。商業轉載請聯繫作者獲得授權,非商業轉載請註明出處。

3 解決代碼

  • java代碼
class Solution {
    public int countDigitOne(int n) {
        int digit = 1, res = 0;
        int high = n / 10,cur = n % 10,low =0;
        while(high != 0 || cur != 0){
            if(cur == 0){
                res += high * digit;
            }
            else if(cur == 1){
                res += high *digit +low + 1;
            }
            else{
                res+=(high + 1) * digit;
            }
            low += cur * digit;
            cur = high % 10;
            high /= 10;
            digit *= 10;
        }
        return res;

    }
}
  • python3代碼
class Solution:
    def countDigitOne(self, n: int) -> int:
        digit, res = 1, 0
        high, cur, low = n // 10, n % 10, 0
        while  high != 0 or cur != 0:
            if cur == 0:
                res += high * digit
            elif cur == 1:
                res += high *digit + low + 1
            else:
                res += (high + 1) * digit
            low = cur * digit +low
            cur = high % 10
            high = high //10
            digit *= 10
        return res
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章