Count Integers With Even Digit Sum Problem
#2180
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 2180.
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
Solution
Approach: Brute Force
Since num is at most 1000, we can simply check every integer from 1 to num. For each one, add up its digits and count it when the sum is even.
Complexity: O(num log num) time (each number has about log num digits) and O(1) extra space.
class Solution:
def countEven(self, num: int) -> int:
ans = 0
for x in range(1, num + 1):
s = 0
while x:
s += x % 10
x //= 10
ans += s % 2 == 0
return ans