LeetCode 2544. Alternating Digit Sum Solution in Java, C++, Python & More | Explanation + Code

CoderIndeed
0
2544. Alternating Digit Sum

Description

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

 

Solutions

Solution 1: Simulation

We can directly simulate the process as described in the problem.

We define an initial symbol sign=1. Starting from the most significant digit, we take out one digit x each time, multiply it by sign, add the result to the answer, then negate sign, and continue to process the next digit until all digits are processed.

The time complexity is O(log n), and the space complexity is O(log n). Here, n is the given number.

PythonJavaC++GoTypeScriptRustC
class Solution: def alternateDigitSum(self, n: int) -> int: return sum((-1) ** i * int(x) for i, x in enumerate(str(n)))(code-box)

Solution 2

PythonRust
class Solution: def alternateDigitSum(self, n: int) -> int: ans, sign = 0, 1 for c in str(n): x = int(c) ans += sign * x sign *= -1 return ans(code-box)

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !