Formatted question description: https://leetcode.ca/all/2180.html

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

Similar Questions:

Solution 1. Brute Force

// OJ: https://leetcode.com/problems/count-integers-with-even-digit-sum/

// Time: O(NlgN)
// Space: O(1)
class Solution {
public:
    int countEven(int num) {
        int ans = 0;
        for (int i = 1; i <= num; ++i) {
            int n = i, sum = 0;
            while (n) {
                sum += n % 10;
                n /= 10;
            }
            ans += sum % 2 == 0;
        }
        return ans;
    }
};

Solution 2. Pattern Finding

num 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
digit sum 1 2 3 4 5 6 7 8 9 1 2 3 4 5 6 7 8 9 10 2 3 4 5 6 7
digit sum is even 0 1 0 1 0 1 0 1 0 0 1 0 1 0 1 0 1 0 0 1 0 1 0 1 0
answer 0 1 1 2 2 3 3 4 4 4 5 5 6 6 7 7 8 8 9 10 10 11 11 12 12

The answer increments when the digit sum of num is even.

We can see that the answer is somewhat related to num / 2 and digitSum(num) % 2. It turns out to be (num - digitSum(num) % 2) / 2.

// OJ: https://leetcode.com/problems/count-integers-with-even-digit-sum/

// Time: O(lgN)
// Space: O(1)
class Solution {
public:
    int countEven(int num) {
        int sum = 0, tmp = num;
        while (num) {
            sum += num % 10;
            num /= 10;
        }
        return (tmp - sum % 2) / 2;
    }
};

Discuss

https://leetcode.com/problems/count-integers-with-even-digit-sum/discuss/1784735

All Problems

All Solutions