Alternating Digit Sum — Solution in Python, Java & C++
Alternating Digit Sum solution explained: step-by-step approach, complexity and code in Python, Java, C++ and JavaScript. An easy problem on math.
Alternating Digit Sum is an easy coding problem on math, asked in Amazon, Adobe and Wipro interviews.
- 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
Hints for Alternating Digit Sum
Hint 1
Work over the decimal string so the most significant digit comes first.
Hint 2
Keep a running sign and flip it after each digit.
Hint 3
Peeling digits with
% 10gives them in the wrong order — the leading sign depends on the digit count.
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
- Convert
nto its decimal string. - Start with
sign = +1; addsign · digitfor each character and negatesign.
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
-1inverts every answer. - Peeling with
% 10needs 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 totalJava
public static int alternateDigitSum(int n) {
String s = Integer.toString(n);
int sum = 0, sign = 1;
for (int i = 0; i < s.length(); i++) {
sum += sign * (s.charAt(i) - '0');
sign = -sign;
}
return sum;
}C++
int alternateDigitSum(int n) {
string s = to_string(n);
int sum = 0, sign = 1;
for (char ch : s) {
sum += sign * (ch - '0');
sign = -sign;
}
return sum;
}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#, Go, Kotlin, PHP, Ruby, Rust, Swift, TypeScript.