Count Integers With Even Digit Sum
The goal is to find the number of positive integers less than or equal to num
whose digit sums are even.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
| class Solution:
def countEven(self, num: int) -> int:
count = 0
# Iterate through all numbers from 1 to num
for i in range(1, num + 1):
digit_sum = 0
# Convert the number to string to iterate through its digits
str_num = str(i)
# Iterate through the digits of the number
for digit in str_num:
digit_sum += int(digit)
# Check if the digit sum is even
if digit_sum % 2 == 0:
count += 1
return count
|
We iterate through all numbers from 1 to num
. For each number, we calculate the sum of its digits by converting it to a string and iterating through its characters. If the sum of the digits is even, we increment the count. Finally, we return the count.