Alternating Digit Sum - 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.

Input & Output

Example 1 — Three Digit Number
$ Input: n = 521
Output: 4
💡 Note: Digits are 5, 2, 1. Signs are +, -, +. So we get +5 + (-2) + (+1) = 5 - 2 + 1 = 4
Example 2 — Four Digit Number
$ Input: n = 111
Output: 1
💡 Note: Digits are 1, 1, 1. Signs are +, -, +. So we get +1 + (-1) + (+1) = 1 - 1 + 1 = 1
Example 3 — Single Digit
$ Input: n = 886
Output: 22
💡 Note: Digits are 8, 8, 6. Signs are +, -, +. So we get +8 + (-8) + (+6) = 8 - 8 + 6 = 6

Constraints

  • 1 ≤ n ≤ 109

Visualization

Tap to expand
Alternating Digit Sumn = 521Step 1: Input number521+5-2+1Step 2: Assign alternating signs (+, -, +)Step 3: Sum = +5 + (-2) + (+1) = 4Result: 4
Understanding the Visualization
1
Input Number
Given positive integer n = 521
2
Assign Signs
Most significant digit positive, then alternate
3
Calculate Sum
Add all digits with their assigned signs
Key Takeaway
🎯 Key Insight: Start with positive sign for the leftmost digit and alternate signs for each subsequent digit
Asked in
LeetCode 15 Microsoft 8
12.0K Views
Medium Frequency
~10 min Avg. Time
245 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