carloscn / structstudy

Leetcode daily trainning by using C/C++/RUST programming.
4 stars 1 forks source link

leetcode2180: Count Integers With Even Digit Sum #353

Open carloscn opened 1 year ago

carloscn commented 1 year ago

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

carloscn commented 1 year ago

Analysis

int32_t count_even(int32_t num)
{
    int32_t ret = 0;

    if (0 == num) {
        return ret;
    }

    for (int32_t i = 1; i <= num; i ++) {
        int32_t e = 0;
        int32_t s = 0;
        int32_t j = i;
        while (j != 0) {
            e = j % 10;
            j = j / 10;
            s += e;
        }
        if (!(s & 1)) {
            ret += 1;
        }
    }

    return ret;
}
carloscn commented 1 year ago

Code

https://review.gerrithub.io/c/carloscn/structstudy/+/1169689 https://github.com/carloscn/structstudy/commit/f04921769da2de11f0c790cebe491c4df7545c4a