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.
Examples
Example 1:
|
|
Example 2:
|
|
Example 3:
|
|
Constraints:
1 <= n <= 109
Solution
Method 1 – Alternating Sign Traversal
Intuition
Assign alternating signs to each digit of n, starting with a positive sign for the most significant digit. This means the first digit is added, the second is subtracted, the third is added, and so on. By traversing the digits from left to right and flipping the sign at each step, we efficiently compute the required sum.
Approach
- Convert n to a string to access each digit from left to right.
- Initialize ans = 0 and sign = 1 (positive).
- For each digit c in the string:
- Add int(c) * sign to ans.
- Flip sign (multiply by -1).
- Return ans.
Example:
For n = 521:
- Digits: 5, 2, 1
- Calculation: (+5) + (-2) + (+1) = 4
Code
|
|
|
|
|
|
|
|
|
|
Complexity
- ⏰ Time complexity: O(D), where D is the number of digits in n.
- 🧺 Space complexity: O(1), ignoring the space for the string representation.