Alternating Digit Sum Solution in C++

Problem Description

Welcome to the world of Alternating Digit Sum, where numbers play a game of tag! The challenge is simple: given a number n, you need to calculate the sum of its digits, but with a twist! You alternate between adding and subtracting each digit, starting with addition.

Imagine you’re at a party, and every time someone says a number, you either cheer (add) or boo (subtract) based on whether it’s in an odd or even position. So, if your friend shouts “1234”, you’d cheer for 1, boo for 2, cheer for 3, and boo for 4. The final score? That’s your Alternating Digit Sum!

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 is straightforward: we loop through each digit of the number n, alternating the sign for each digit. We start with a positive sign, and for each digit, we multiply the sign by -1 to switch it. The digit is then added to our answer based on the current sign. Finally, we return the total sum, ensuring the last sign is applied correctly.

Time and Space Complexity

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

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

Real-World Example

Let’s say you’re counting your friends at a party, but you want to keep track of who’s being nice and who’s being a little too rowdy. You cheer for every odd-numbered friend and boo the even ones. If you have 1234 friends, your final score would be:

1 (cheer) – 2 (boo) + 3 (cheer) – 4 (boo) = -2.

So, you end up with a score of -2, which means you might need to have a chat with your even-numbered friends!

Similar Problems

If you enjoyed this problem, you might also like these:

  • 2-Sum Solution in C++
  • 3-Sum Solution in C++