Alternating Digit Sum

The task is to sum all the digits of a given integer n, but with alternating signs starting with a positive sign for the most significant digit.

Here’s a simple way to accomplish this:

  1. Convert the integer to a string to easily access its individual digits.
  2. Iterate through the string, converting each digit back to an integer.
  3. Alternate the sign of each digit by using a sign variable that flips between 1 and -1.
  4. Sum the digits, taking the sign into account.

Implementation

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
class Solution:
    def alternateDigitSum(self, n: int) -> int:
        # Convert n to string
        n_str = str(n)

        # Initialize the sum and sign variables
        total_sum = 0
        sign = 1

        # Iterate through the digits and sum them with alternating signs
        for digit in n_str:
            total_sum += sign * int(digit)
            sign *= -1 # Flip the sign

        return total_sum

Explanation

  • For Input: n = 521
  • Iteration through digits: (+5) + (-2) + (+1)
  • Output: 4

This code ensures that each digit is processed with the correct sign. Since we iterate through each digit exactly once, the complexity of this solution is ( O(m) ), where ( m ) is the number of digits in n.