Skip to content

2180. Count Integers With Even Digit Sum 👍

  • Time: $O(\log\texttt{num})$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
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;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
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;
  }
}
1
2
3
4
5
6
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))