Alternating Digit Sum Solution in Python


class Solution:
    def alternateDigitSum(self, n: int) -> int:
        ans = 0
        sign = 1

        while n > 0:
            sign *= -1
            ans += n % 10 * sign
            n //= 10

        return sign * ans
    

Problem Description

Welcome to the world of Alternating Digit Sum, where numbers are not just digits but a rollercoaster of emotions! Imagine you have a number, and you want to sum its digits in a way that alternates between adding and subtracting. Sounds like a fun party trick, right?

For instance, if you have the number 1234, you would calculate the sum as follows:

  • Start with 1 (add it)
  • Then 2 (subtract it)
  • Next 3 (add it)
  • Finally 4 (subtract it)

So, the calculation would be: 1 - 2 + 3 - 4 = -2.

Now, if you think this is just a math problem, think again! It’s like trying to decide whether to eat pizza or salad for dinner—one moment you’re adding toppings, the next you’re subtracting calories.

Approach Explanation

The approach here is as straightforward as your morning coffee routine. We initialize a variable ans to store our result and a sign variable to keep track of whether we’re adding or subtracting. As we loop through each digit of the number, we alternate the sign and update our answer accordingly.

  1. Extract the last digit: We use n % 10 to get the last digit.
  2. Update the answer: Depending on the current sign, we either add or subtract the digit from ans.
  3. Remove the last digit: We use integer division n //= 10 to drop the last digit.
  4. Repeat until there are no digits left.

Time and Space Complexity

Time Complexity: O(d), where d is the number of digits in the number n. We process each digit exactly once.

Space Complexity: O(1), as we are using a constant amount of space regardless of the input size.

Real-World Example

Imagine you’re at a party, and you’re trying to keep track of how many snacks you’ve eaten. You start with a plate of chips (add), then you grab a cookie (subtract), followed by a slice of pizza (add), and finally, a piece of cake (subtract). By the end of the night, you’re left wondering if you gained or lost weight! This is essentially what the Alternating Digit Sum is doing with numbers—keeping track of the ups and downs!

Similar Problems

2-Sum Solution in Python
3-Sum Solution in Python
4-Sum Solution in Python
Add Two Numbers Solution in Python
Palindrome Number Solution in Python