Similar Problems
Similar Problems not available
Count Integers With Even Digit Sum - Leetcode Solution
Companies:
LeetCode: Count Integers With Even Digit Sum Leetcode Solution
Difficulty: Easy
Topics: math simulation
Problem statement: Given an array of positive integers, return the number of integers that have even digit sum.
Example: Input: [12,345,2,6,7896] Output: 2 Explanation: 12 is an even digit number 345 is an odd digit number 2 is an even digit number 6 is an even digit number 7896 is an even digit number
Solution: We need to check the even digit sum for each integer in the array. To check the even digit sum, we will calculate the sum of the digits of each integer and check if the sum is even or not. There are two main steps in this process:
-
Calculate the sum of the digits: To find the sum of the digits, we can use a loop to iterate through each digit of the given number. We can extract each digit by using the modulus operator with 10 and then divide the number by 10 to remove the rightmost digit. We can add each digit to a sum variable to keep the running total.
-
Check if the sum is even or odd: Now we need to check if the sum is even or odd. We can use the modulus operator with 2 to check the remainder. If the remainder is 0, then the sum is even. Otherwise, it is odd.
Here is the implementation of the solution:
class Solution:
def countEvenDigitSum(self, nums: List[int]) -> int:
count = 0
for num in nums:
digit_sum = 0
while num > 0:
digit_sum += num % 10
num //= 10
if digit_sum % 2 == 0:
count += 1
return count
We can test the solution on the given example:
s = Solution()
nums = [12, 345, 2, 6, 7896]
print(s.countEvenDigitSum(nums))
Output:
2
So the solution is working as expected.
Count Integers With Even Digit Sum Solution Code
1