carloscn / structstudy

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

leetcode2544: Alternating Digit Sum #416

Open carloscn opened 1 year ago

carloscn commented 1 year ago

Description

You are given a positive integer n. Each digit of n has a sign according to the following rules:

The most significant digit is assigned a positive sign. Each other digit has an opposite sign to its adjacent digits. Return the sum of all digits with their corresponding sign.

Example 1:

Input: n = 521 Output: 4 Explanation: (+5) + (-2) + (+1) = 4.

Example 2:

Input: n = 111 Output: 1 Explanation: (+1) + (-1) + (+1) = 1.

Example 3:

Input: n = 886996 Output: 0 Explanation: (+8) + (-8) + (+6) + (-9) + (+9) + (-6) = 0.

Constraints:

1 <= n <= 109

carloscn commented 1 year ago

Analysis

static int32_t alternate_digit_sum(int32_t n)
{
    int32_t ret = 0;

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

    int32_t d = n, i = 0;
    while (d != 0) {
        ret += ((((i ++) & 0x1) ? -1 : 1)) * (d % 10);
        d /= 10;
    }

finish:
    return ret;
}
carloscn commented 1 year ago

Code

https://review.gerrithub.io/c/carloscn/structstudy/+/1171925 https://github.com/carloscn/structstudy/commit/36ffc0035b6cd97263546afd6e839e11d985f54a