Alternating Digit Sum — LeetCode 2544 Python Solution

EasyMath
Problem
#2544
Reading time
2 min

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

Python
class Solution:
    def alternateDigitSum(self, n: int) -> int:
        return sum((-1) ** i * int(x) for i, x in enumerate(str(n)))

Complexity

MeasureComplexity
TimeO(\log n)
SpaceO(\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.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview