Alternating Digit Sum - Problem

You are given a positive integer n. Imagine each digit as having a sign (positive or negative) based on its position:

  • The most significant digit (leftmost) is always positive
  • Each subsequent digit has the opposite sign of the digit before it

Your task is to calculate the alternating sum of all digits with their corresponding signs.

Example: For n = 521:
• Digit 5 (position 0): +5
• Digit 2 (position 1): -2
• Digit 1 (position 2): +1
• Result: 5 - 2 + 1 = 4

Input & Output

example_1.py — Basic Case
$ Input: n = 521
Output: 4
💡 Note: The digits are 5, 2, 1 with signs +, -, + respectively. So the sum is +5 - 2 + 1 = 4.
example_2.py — Even Number of Digits
$ Input: n = 111
Output: 1
💡 Note: The digits are 1, 1, 1 with signs +, -, + respectively. So the sum is +1 - 1 + 1 = 1.
example_3.py — Single Digit
$ Input: n = 886996
Output: 0
💡 Note: The digits are 8,8,6,9,9,6 with signs +,-,+,-,+,- respectively. So the sum is +8-8+6-9+9-6 = 0.

Visualization

Tap to expand
Alternating Digit Sum PatternExample: n = 5215Position 0+52Position 1-21Position 2+1Pattern RuleEven positions (0, 2, 4, ...) → Positive (+)Odd positions (1, 3, 5, ...) → Negative (-)Result: 5 - 2 + 1 = 4
Understanding the Visualization
1
Identify Positions
Number the digit positions from left starting at 0
2
Apply Sign Rule
Even positions (0,2,4...) are positive, odd positions (1,3,5...) are negative
3
Calculate Sum
Sum all digits with their corresponding signs
Key Takeaway
🎯 Key Insight: The sign alternates based on position - we can determine this mathematically without needing to track state!

Time & Space Complexity

Time Complexity
⏱️
O(d)

Where d is the number of digits. We process each digit exactly once.

n
2n
Linear Growth
Space Complexity
O(1)

Only using a few variables regardless of input size

n
2n
Linear Space

Constraints

  • 1 ≤ n ≤ 109
  • n is a positive integer
  • The number will have at most 10 digits
Asked in
Google 15 Microsoft 12 Amazon 8 Meta 5
28.5K Views
Medium Frequency
~8 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen