2544. Alternating Digit Sum LeetCode Solution

In this guide, you will get 2544. Alternating Digit Sum LeetCode Solution with the best time and space complexity. The solution to Alternating Digit Sum problem is provided in various programming languages like C++, Java, and Python. This will be helpful for you if you are preparing for placements, hackathons, interviews, or practice purposes. The solutions provided here are very easy to follow and include detailed explanations.

Table of Contents

  1. Problem Statement
  2. Complexity Analysis
  3. Alternating Digit Sum solution in C++
  4. Alternating Digit Sum solution in Java
  5. Alternating Digit Sum solution in Python
  6. Additional Resources
2544. Alternating Digit Sum LeetCode Solution image

Problem Statement of Alternating Digit Sum

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 <= 109

Complexity Analysis

  • Time Complexity: O(\log n)
  • Space Complexity: O(1)

2544. Alternating Digit Sum LeetCode Solution in C++

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;
  }
};
/* code provided by PROGIEZ */

2544. Alternating Digit Sum LeetCode Solution in Java

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;
  }
}
// code provided by PROGIEZ

2544. Alternating Digit Sum LeetCode 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
# code by PROGIEZ

Additional Resources

Happy Coding! Keep following PROGIEZ for more updates and solutions.