统计各位数字之和为偶数的整数个数【LC2180】
Given a positive integer
num, return the number of positive integers less than or equal tonumwhose digit sums are even.The digit sum of a positive integer is the sum of all its digits.
加油啊 惰性起来了 想回学校:(
暴力
-
思路:暴力统计区间[1,num][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(lognum∗num)O(log num*num)O(lognum∗num)
-
空间复杂度:O(1)O(1)O(1)
-
-
数学
-
思路:
- 首先找规律,除了1−91-91−9内有4个数的数位和为偶数,其他每10个数内均有5个数的数位和为偶数,比如10-19,20-29……。
- 因此可以先算出num中有多少个10的倍数,假设num=a∗10+bnum=a*10+bnum=a∗10+b,那么在[1,a∗10−1][1,a*10-1][1,a∗10−1]的区间内共有a∗5−1a*5-1a∗5−1个数的数位和为偶数
- 然后计算区间[a∗10,a∗10+b][a*10,a*10+b][a∗10,a∗10+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][a∗10,a∗10+b]内的合法数个数,假设数位和为
s,那么贡献为(b+2-s&1)/2class 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(lognum)O(log num)O(lognum)
-
空间复杂度:O(1)O(1)O(1)
-
-

文章讲述了如何计算小于或等于给定正整数num的、其数位之和为偶数的正整数数量。提供了两种解决方案:暴力求解方法,遍历所有数并检查数位和;以及数学优化方法,利用数位和的奇偶性规律进行计算,提高了效率。
1271

被折叠的 条评论
为什么被折叠?



