Problem

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.

Examples

Example 1:

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

Example 2:

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

Example 3:

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

Constraints:

  • 1 <= n <= 109

Solution

Method 1 – Alternating Sign Traversal

Intuition

Assign alternating signs to each digit of n, starting with a positive sign for the most significant digit. This means the first digit is added, the second is subtracted, the third is added, and so on. By traversing the digits from left to right and flipping the sign at each step, we efficiently compute the required sum.

Approach

  1. Convert n to a string to access each digit from left to right.
  2. Initialize ans = 0 and sign = 1 (positive).
  3. For each digit c in the string:
    • Add int(c) * sign to ans.
    • Flip sign (multiply by -1).
  4. Return ans.

Example:

For n = 521:

  • Digits: 5, 2, 1
  • Calculation: (+5) + (-2) + (+1) = 4

Code

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
class Solution {
public:
    int alternateDigitSum(int n) {
        string s = to_string(n);
        int ans = 0, sign = 1;
        for (char c : s) {
            ans += (c - '0') * sign;
            sign *= -1;
        }
        return ans;
    }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
class Solution {
    public int alternateDigitSum(int n) {
        String s = Integer.toString(n);
        int ans = 0, sign = 1;
        for (char c : s.toCharArray()) {
            ans += (c - '0') * sign;
            sign *= -1;
        }
        return ans;
    }
}
1
2
3
4
5
6
7
8
9
class Solution:
    def alternateDigitSum(self, n: int) -> int:
        s = str(n)
        ans = 0
        sign = 1
        for c in s:
            ans += int(c) * sign
            sign *= -1
        return ans
1
2
3
4
5
6
7
8
9
func alternateDigitSum(n int) int {
    s := strconv.Itoa(n)
    ans, sign := 0, 1
    for _, c := range s {
        ans += int(c-'0') * sign
        sign *= -1
    }
    return ans
}
1
2
3
4
5
6
7
8
9
function alternateDigitSum(n: number): number {
    const s = n.toString();
    let ans = 0, sign = 1;
    for (const c of s) {
        ans += Number(c) * sign;
        sign *= -1;
    }
    return ans;
}

Complexity

  • Time complexity: O(D), where D is the number of digits in n.
  • 🧺 Space complexity: O(1), ignoring the space for the string representation.