Skip to content

2180. Count Integers With Even Digit Sum

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

Analysis

We can use the bitwise operation to save some space for a big integer's sum (although a big integer's digit sum is always less than the big integer itself). We know 1. even + even = even 2. odd + odd = even 3. even + odd = odd

Using this property, we don't really need to calculate the sum, but just to check each digit's parity.

  • Time: O(n \times d) each number runs digits times for checking the sum
  • Space: O(1)

Code

class Solution {
public:
    int countEven(int num) {
        int cnt = 0;
        for (int i = 1; i <= num; ++i) {
            bool even = true;
            int a = i;
            while (a) {
                even = (even != (a & 1));
                a /= 10;
            }
            if (even) cnt ++;
        }
        return cnt;
    }
};

Last update: March 31, 2022