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: 6
💡 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 Sum INPUT n = 521 5 + 2 - 1 + pos 0 pos 1 pos 2 Sign Rules: First digit: + (positive) Alternating: +, -, +, -, ... Input Value n = 521 ALGORITHM STEPS 1 Convert to string "521" to get digits 2 Init sign = +1 Start with positive 3 Loop through digits Add digit * sign 4 Flip sign sign = sign * (-1) Calculation: sum = 0 sum = 0 + (5 * +1) = 5 sum = 5 + (2 * -1) = 3 sum = 3 + (1 * +1) = 4 FINAL RESULT Expression: +5 -2 +1 = 4 Output Value return 4 OK - Verified! Key Insight: The most significant digit (leftmost) always gets a positive sign. Each subsequent digit alternates: positive, negative, positive, negative... The pattern depends only on position, not digit value. Time Complexity: O(log n) where log n is the number of digits. TutorialsPoint - Alternating Digit Sum | Optimal Solution
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