LeetCode 1067. 范围内的数字计数
生活随笔
收集整理的這篇文章主要介紹了
LeetCode 1067. 范围内的数字计数
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
文章目錄
- 1. 題目
- 2. 解題
1. 題目
給定一個在 0 到 9 之間的整數 d,和兩個正整數 low 和 high 分別作為上下界。
返回 d 在 low 和 high 之間的整數中出現的次數,包括邊界 low 和 high。
示例 1: 輸入:d = 1, low = 1, high = 13 輸出:6 解釋: 數字 d=1 在 1,10,11,12,13 中出現 6 次。 注意 d=1 在數字 11 中出現兩次。示例 2: 輸入:d = 3, low = 100, high = 250 輸出:35 解釋: 數字 d=3 在 103,113,123,130,131,...,238,239,243 出現 35 次。提示: 0 <= d <= 9 1 <= low <= high <= 2×10^8來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/digit-count-in-range
著作權歸領扣網絡所有。商業轉載請聯系官方授權,非商業轉載請注明出處。
2. 解題
劍指Offer - 面試題43. 1~n整數中1出現的次數(找規律+公式)
class Solution { public:int digitsCount(int d, int low, int high) {return countDigit(high, d) - countDigit(low-1, d);}int countDigit(int n, int d) {if(n < 0)return 0;int high, cur, low;long sum = 0, i = 1;while(n/i){high = n/(i*10);cur = n/i%10;low = n%i; //low = n-n/i*i; //或者if(cur < d)sum += high*i;else if(cur == d)sum += high*i+low+1;elsesum += (high+1)*i;if(d == 0)//特殊情況,減掉當前以0開頭的個數sum -= i;i *= 10;}return sum;} };我的CSDN博客地址 https://michael.blog.csdn.net/
長按或掃碼關注我的公眾號(Michael阿明),一起加油、一起學習進步!
總結
以上是生活随笔為你收集整理的LeetCode 1067. 范围内的数字计数的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: LeetCode 第 34 场双周赛(3
- 下一篇: LeetCode 第 201 场周赛(3