Alternating Digit Sum — Easy Problem & Solution

Give the digits of n alternating signs, starting with a plus on the most significant digit, and return their sum.

  • Difficulty: Easy
  • Topics: Math
  • Asked at: Amazon, Adobe, Wipro
  • Time limit: 2 s
  • Memory limit: 256 MB
  • Languages: JavaScript, TypeScript, Python, Java, C++, C, C#, Go, Kotlin, Swift, Rust, PHP and Ruby

Problem statement

Give the digits of n alternating signs, starting with a plus on the most significant digit, and return their sum.

Example 1

Input: n = 521
Output: 4
Explanation: 5 − 2 + 1.

Example 2

Input: n = 111
Output: 1
Explanation: 1 − 1 + 1.

Example 3

Input: n = 886996
Output: 0
Explanation: 8 − 8 + 6 − 9 + 9 − 6.

Constraints

  • 1 <= n <= 1000000000

How to solve Alternating Digit Sum

Render the number as a string so the digits arrive most-significant first, then add them with a flipping sign.

Approach

  1. Convert n to its decimal string.
  2. Start with sign = +1; add sign · digit for each character and negate sign.

Why it works

The sign of a digit depends on its position from the left, which the string gives directly. Extracting digits arithmetically with n % 10 yields them right-to-left, so the starting sign would depend on the parity of the digit count — correct but easier to get wrong.

Complexity

  • Time — O(d) in the number of digits
  • Space — O(d)

Pitfalls

  • Starting the sign at -1 inverts every answer.
  • Peeling with % 10 needs the digit count to decide the first sign.
  • The result can be negative, and the sum stays well inside int.

Reference solution

Python

def alternateDigitSum(n: int) -> int:
    total, sign = 0, 1
    for ch in str(n):
        total += sign * int(ch)
        sign = -sign
    return total

JavaScript

var alternateDigitSum = function(n) {
    var s = String(n);
    var sum = 0, sign = 1;
    for (var i = 0; i < s.length; i++) {
        sum += sign * (s.charCodeAt(i) - 48);
        sign = -sign;
    }
    return sum;
};

Also on the editorial tab: C, C#, C++, Go, Java, Kotlin, PHP, Ruby, Rust, Swift, TypeScript.

All 213 math problems · the whole catalogue