Count Integers With Even Digit Sum
LeetCode 2298 | Difficulty: Easyβ
EasyProblem Descriptionβ
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`
Topics: Math, Simulation
Approachβ
Mathematicalβ
Look for mathematical patterns or formulas. Consider: modular arithmetic, GCD/LCM, prime factorization, combinatorics, or geometric properties.
When to use
Problems with clear mathematical structure, counting, number properties.
Solutionsβ
Solution 1: C# (Best: 21 ms)β
| Metric | Value |
|---|---|
| Runtime | 21 ms |
| Memory | 25.1 MB |
| Date | 2022-02-21 |
Solution
public class Solution {
public int CountEven(int num) {
int i = 2, result = 0;
while(i<=num)
{
int temp = i; int sum = 0;
while(temp>0)
{
sum += temp%10;
temp/=10;
}
if(sum%2 ==0) result++;
i++;
}
return result;
}
}
Complexity Analysisβ
| Approach | Time | Space |
|---|---|---|
| Solution | $O(n)$ | $O(1) to O(n)$ |
Interview Tipsβ
Key Points
- Start by clarifying edge cases: empty input, single element, all duplicates.
- LeetCode provides 2 hint(s) for this problem β try solving without them first.
π‘ Hints
Hint 1: Iterate through all integers from 1 to num.
Hint 2: For any integer, extract the individual digits to compute their sum and check if it is even.