#2544

Alternating Digit Sum

newbie · 295 · lc easy +20 · verified · 69% accepted · 479 likes · top 76%

Description

Given a positive integer n, assign signs to its digits so that the most significant digit is positive and each subsequent digit alternates sign. Return the resulting signed digit sum.

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.

Code

1
2
3