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