【每日一题Day79】LC2180统计各位数字之和为偶数的整数个数 | 数学 暴力

统计各位数字之和为偶数的整数个数【LC2180】

Given a positive integer num, return the number of positive integers less than or equal to num whose digit sums are even.

The digit sum of a positive integer is the sum of all its digits.

加油啊 惰性起来了 想回学校:(

暴力

  • 思路:暴力统计区间 [ 1 , n u m ] [1,num] [1,num]内每个数的数位之和是偶数的个数

  • 实现

    class Solution {
        public int countEven(int num) {
            int count = 0;
            for (int i = 1; i <= num; i++){
                 if (check(i)){
                     count++;
                 }
            }
            return count;  
    
        }
        public boolean check(int num){
            int sum = 0;
            while (num != 0 ){
                sum += num % 10;
                num /= 10;
            }
            return sum % 2 == 0;
        }
        
    }
    
    • 复杂度

      • 时间复杂度: O ( l o g n u m ∗ n u m ) O(log num*num) O(lognumnum)

      • 空间复杂度: O ( 1 ) O(1) O(1)

数学

  • 思路:

    • 首先找规律,除了 1 − 9 1-9 19内有4个数的数位和为偶数,其他每10个数内均有5个数的数位和为偶数,比如10-19,20-29……。
    • 因此可以先算出num中有多少个10的倍数,假设 n u m = a ∗ 10 + b num=a*10+b num=a10+b,那么在 [ 1 , a ∗ 10 − 1 ] [1,a*10-1] [1,a101]的区间内共有 a ∗ 5 − 1 a*5-1 a51个数的数位和为偶数
    • 然后计算区间 [ a ∗ 10 , a ∗ 10 + b ] [a*10,a*10+b] [a10,a10+b]内有多少个数的数位和为偶数
      • 如果前面的数字的数位和为偶数,那么该区间内对结果的贡献为 ⌊ b / 2 + 1 ⌋ = ⌊ ( b + 2 ) / 2 ⌋ \lfloor b/2+1 \rfloor= \lfloor(b+2)/2\rfloor b/2+1=⌊(b+2)/2
      • 如果前面的数字的数位和为奇数,那么该区间内对结果的贡献为 ⌊ ( b + 1 ) / 2 ⌋ \lfloor(b+1)/2\rfloor ⌊(b+1)/2
    • 累加可得最终结果
  • 实现

    可通过一行代码获得 [ a ∗ 10 , a ∗ 10 + b ] [a*10,a*10+b] [a10,a10+b]内的合法数个数,假设数位和为s,那么贡献为(b+2-s&1)/2

    class Solution {
        public int countEven(int num) {
            int a = num / 10, b = num % 10;
            int x = a, s = 0;
            while (x > 0){
                s += x % 10;
                x /= 10;
            }
            return a * 5 - 1 + (b + 2 - (s & 1)) / 2;
    
        }
        
    }
    
    • 复杂度

      • 时间复杂度: O ( l o g n u m ) O(log num) O(lognum)

      • 空间复杂度: O ( 1 ) O(1) O(1)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值