Alternating Digit Sum Solution in Java


Problem Description

So, you think you can just add up the digits of a number? Well, think again! The Alternating Digit Sum problem is here to throw a wrench in your simple math skills. Imagine you have a number, say 1234. Instead of just adding the digits like a normal person, you have to alternate between adding and subtracting them. So, for 1234, it would be 1 – 2 + 3 – 4. Sounds like a fun party game, right?

In real life, this is like trying to decide whether to eat the last slice of pizza or leave it for your friend. One minute you’re all about sharing (subtracting), and the next, you’re like, “Nah, I deserve this!” (adding).

Code Solution


class Solution {
  public int alternateDigitSum(int n) {
    int ans = 0;
    int sign = 1;

    for (; n > 0; n /= 10) {
      sign *= -1;
      ans += sign * n % 10;
    }

    return sign * ans;
  }
}
    

Approach

The approach here is as straightforward as it gets. We loop through each digit of the number, alternating the sign with each iteration. The sign variable starts at 1 (for addition) and flips to -1 (for subtraction) with each digit processed. We keep adding or subtracting the last digit of n until there are no digits left.

Time and Space Complexity

Time Complexity: O(log n) – We are essentially dividing the number by 10 in each iteration, which reduces the number of digits logarithmically.

Space Complexity: O(1) – We are using a constant amount of space regardless of the input size.

Real-World Example

Let’s say you’re at a carnival, and you have a ticket that allows you to go on rides. Each ride costs you a ticket, but some rides give you a ticket back! If you go on rides in the order of 1 ticket, lose 2 tickets, gain 3 tickets, and lose 4 tickets, you’d end up with a net ticket count of 1 – 2 + 3 – 4 = -2. Just like the Alternating Digit Sum, you’re alternating between gaining and losing tickets!

Similar Problems

If you enjoyed this problem, you might want to check out these similar challenges:

  • 2-Sum Solution in Java
  • 3-Sum Solution in Java