Skip to main content
Back to problems
Leetcode
Medium
Math
Strings
Alternating Digit Sum

Compute the alternating sum of a number’s digits, starting from the most significant digit with a positive sign.

Acceptance 0%
Problem Statement

Given a decimal number, evaluate the sum of its digits with alternating signs from left to right. The first digit is added, the second is subtracted, the third is added again, and so on until all digits are processed.

Return the final total.

Input Format

  • One non-negative integer.

Output Format

  • One integer equal to the alternating digit sum.

Constraints

  • Use one pass over the digits.
  • The number is non-negative.
Examples
Sample cases returned by the problem API.

Example 1

Input

n = 521

Output

4

Explanation

5 - 2 + 1 = 4.

Example 2

Input

n = 1111

Output

0

Explanation

1 - 1 + 1 - 1 = 0.

Show 1 more example

Example 3

Input

n = 886996

Output

0

Explanation

8 - 8 + 6 - 9 + 9 - 6 = 0.

Premium problem context

Unlock deeper context for this problem

Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.

Guided hints
Editorial and discussion links
Concept map and variants
Sign in to unlock
Track your progress
Sign in to bookmark this problem, save notes, and manage its revision plan.