2180. Count Integers With Even Digit Sum LeetCode Solution

In this guide, you will get 2180. Count Integers With Even Digit Sum LeetCode Solution with the best time and space complexity. The solution to Count Integers With Even Digit Sum problem is provided in various programming languages like C++, Java, and Python. This will be helpful for you if you are preparing for placements, hackathons, interviews, or practice purposes. The solutions provided here are very easy to follow and include detailed explanations.

Table of Contents

  1. Problem Statement
  2. Complexity Analysis
  3. Count Integers With Even Digit Sum solution in C++
  4. Count Integers With Even Digit Sum solution in Java
  5. Count Integers With Even Digit Sum solution in Python
  6. Additional Resources
2180. Count Integers With Even Digit Sum LeetCode Solution image

Problem Statement of 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

Complexity Analysis

  • Time Complexity: O(\log\texttt{num})
  • Space Complexity: O(1)

2180. Count Integers With Even Digit Sum LeetCode Solution in C++

class Solution {
 public:
  int countEven(int num) {
    return (num - getDigitSum(num) % 2) / 2;
  }

 private:
  int getDigitSum(int num) {
    int digitSum = 0;
    while (num > 0) {
      digitSum += num % 10;
      num /= 10;
    }
    return digitSum;
  }
};
/* code provided by PROGIEZ */

2180. Count Integers With Even Digit Sum LeetCode Solution in Java

class Solution {
  public int countEven(int num) {
    if (getDigitSum(num) % 2 == 0)
      return num / 2;
    return (num - 1) / 2;
  }

  private int getDigitSum(int num) {
    int digitSum = 0;
    while (num > 0) {
      digitSum += num % 10;
      num /= 10;
    }
    return digitSum;
  }
}
// code provided by PROGIEZ

2180. Count Integers With Even Digit Sum LeetCode Solution in Python

class Solution:
  def countEven(self, num: int) -> int:
    return (num - self._getDigitSum(num) % 2) // 2

  def _getDigitSum(self, num: int) -> int:
    return sum(int(digit) for digit in str(num))
# code by PROGIEZ

Additional Resources

See also  1920. Build Array from Permutation LeetCode Solution

Happy Coding! Keep following PROGIEZ for more updates and solutions.