解题记录 LeetCode 数字 1 的个数 数学规律题

题目链接: https://leetcode-cn.com/problems/number-of-digit-one/
题意: 求小于等于 n 的数中1出现的个数
思路: 暴力超时, n 范围 2 * 1e9, 所以需要找规律, 易发现个位上每增加十个数, 个位就会出现一次1, 十位上每增加100个数会出现10次1, 以此类推, 但是由于 n 不是一个能被10整除的数, 所以还有末尾细节需要处理

代码:

class Solution {
    
    
    public int countDigitOne(int n) {
    
    
       int ans = 0;
       for(long i = 1; i <= n; i *= 10) {
    
    
           ans += ((n / (i * 10)) * i + Math.min(i, Math.max(0, n % (i * 10) - i + 1)));
       }
       return ans;
    }
}

总结: 可以拓展求 5 出现的个数等等

猜你喜欢

转载自blog.csdn.net/qq_45560445/article/details/118514765
今日推荐