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
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
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code