Alternating Digit Sum — LeetCode 2544 Python Solution
- Problem
- #2544
- Pattern
- Math and Number Theory
- Reading time
- 2 min
- Source
- leetcode.com
The problem
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.
Example
- Input
- n = 521
- Output
- 4
- Explanation
- (+5) + (-2) + (+1) = 4.
Python solution
class Solution:
def alternateDigitSum(self, n: int) -> int:
return sum((-1) ** i * int(x) for i, x in enumerate(str(n)))Complexity
| Measure | Complexity |
|---|---|
| Time | O(\log n) |
| Space | O(\log n) auxiliary |
Pattern: Math and Number Theory
Find the closed form, the invariant, or the modular identity — and skip the loop entirely. LeetCode 2544. Alternating Digit Sum is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Math.
The math and number theory guide has the Python template for the pattern and the 485 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 2544. Alternating Digit Sum?
- LeetCode 2544. Alternating Digit Sum is rated Easy on LeetCode.
- What is the time complexity of LeetCode 2544. Alternating Digit Sum?
- The Python solution on this page runs in O(\log n).
- What is the space complexity of LeetCode 2544. Alternating Digit Sum?
- The Python solution on this page uses O(\log n) auxiliary space.
- What topics does LeetCode 2544. Alternating Digit Sum cover?
- LeetCode 2544. Alternating Digit Sum is tagged Math on LeetCode.