Leetcode 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.
num
be zero?
num
is a positive integer.num
?
num
inclusive.num
?
num
is within the constraints as specified in the problem, typically meaning it can be up to (10^6).To solve this problem, we need to count how many integers between 1 and num
have an even digit sum. We will do the following:
num
.We’ll need a helper function to compute the sum of digits of a number. Our main function can then use this helper function to determine if the digit sum is even and keep track of the count of such integers.
Here is the C++ code to solve the problem:
#include <iostream>
class Solution {
public:
int countEven(int num) {
int evenCount = 0;
for (int i = 1; i <= num; ++i) {
if (isEvenDigitSum(i)) {
++evenCount;
}
}
return evenCount;
}
private:
bool isEvenDigitSum(int number) {
int sum = 0;
while (number > 0) {
sum += number % 10;
number /= 10;
}
return sum % 2 == 0;
}
};
// Example usage:
// int main() {
// Solution sol;
// int num = 30;
// std::cout << "Count of integers with even digit sum up to " << num << " is: " << sol.countEven(num) << std::endl;
// return 0;
// }
The time complexity of this solution is (O(n \log n)):
num
, which takes (O(n)).Thus, the overall time complexity is (O(n \log n)). This solution is efficient enough for the typical constraint (1 \leq num \leq 10^6).
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?