Alternating Digit Sum Problem
#2544
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 2544.
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.
Example 1:
Input: n = 521
Output: 4
Explanation: (+5) + (-2) + (+1) = 4.
Example 2:
Input: n = 111
Output: 1
Explanation: (+1) + (-1) + (+1) = 1.
Example 3:
Input: n = 886996
Output: 0
Explanation: (+8) + (-8) + (+6) + (-9) + (+9) + (-6) = 0.
Constraints:
1 <= n <= 10^9
Solution
Approach: Simulation
The leading digit gets + and signs alternate from there. Peeling digits off from the least significant end is easiest, but then we do not know the leading digit's position up front. So give the last digit +, flip the sign after each digit, and track it in sign. After the loop sign is the sign the next digit would have, which is the opposite of the leading digit's sign in this reversed run, so multiplying the total by -sign makes the leading digit positive.
Complexity: O(log n) time and O(1) extra space.
class Solution:
def alternateDigitSum(self, n: int) -> int:
return sum((-1) ** i * int(x) for i, x in enumerate(str(n)))