2180. Count Integers With Even Digit Sum
Easy
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.
Example 1:
Input: num = 4
Output:
2
Explanation:
The only integers less than or equal to 4 whose digit sums are even are 2 and 4.
Example 2:
Input: num = 30
Output:
14
Explanation:
The 14 integers less than or equal to 30 whose digit sums are even are
2, 4, 6, 8, 11, 13, 15, 17, 19, 20, 22, 24, 26, and 28.
Constraints:
1 <= num <= 1000
Runtime: 0 ms, faster than 100%
Memory Usage: 1.9 MB, less than 90.91%
func countEven(num int) int {
if num < 10 { return num / 2 }
res := 4
for i:= 11 ; i <= num; i++ {
if check(i) { res++ }
}
return res
}
func check(n int) bool {
sum := 0
for n > 0 {
sum += n % 10
n /= 10
}
if sum % 2 == 0 {
return true
} else {
return false
}
}