统计各位数字之和为偶数的整数个数【LC2180】
Given a positive integer
num
, return the number of positive integers less than or equal tonum
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(lognum∗num)
-
空间复杂度: O ( 1 ) O(1) O(1)
-
-
数学
-
思路:
- 首先找规律,除了 1 − 9 1-9 1−9内有4个数的数位和为偶数,其他每10个数内均有5个数的数位和为偶数,比如10-19,20-29……。
- 因此可以先算出num中有多少个10的倍数,假设 n u m = a ∗ 10 + b num=a*10+b num=a∗10+b,那么在 [ 1 , a ∗ 10 − 1 ] [1,a*10-1] [1,a∗10−1]的区间内共有 a ∗ 5 − 1 a*5-1 a∗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)/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)
-
-