We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Alternating Digit Sum

Number: 2630

Difficulty: Easy

Paid? No

Companies: eBay


Problem Description

Given a positive integer n, each digit of n is assigned a sign: the most significant digit is positive, and every subsequent digit alternates in sign (i.e. negative, positive, negative, ...). The objective is to calculate the sum of the digits taking these alternating signs into account.


Key Insights

  • The digits of the number can be processed sequentially from left to right.
  • The most significant digit is always positive.
  • Every following digit alternates between a negative and a positive sign.
  • Converting the integer to a string simplifies accessing each digit.
  • The time complexity is minimal since the number of digits is limited (n ≤ 10^9).

Space and Time Complexity

Time Complexity: O(d) where d is the number of digits in the number (at most 10 digits). Space Complexity: O(d) if converting the integer to a string, otherwise O(1).


Solution

The approach is to convert the given integer n into a string so that each digit can be easily iterated. Initialize the sum as zero and set the first sign as positive (i.e., +1). For every digit in the string, convert it back to an integer, multiply it by the current sign, and add it to the total sum. After processing each digit, flip the sign (from positive to negative or vice-versa) by multiplying the sign by -1. This will ensure that the alternating sign pattern is maintained. Finally, return the computed total sum.


Code Solutions

# Function to compute the alternating digit sum
def alternatingDigitSum(n):
    # Convert the number to a string to iterate over each digit
    num_str = str(n)
    total = 0
    sign = 1  # Starting sign is positive
    # Iterate over each digit in the string representation
    for char in num_str:
        total += sign * int(char)  # Multiply the digit by its corresponding sign
        sign *= -1  # Alternate the sign for the next digit
    return total

# Example usage:
result = alternatingDigitSum(521)  # Expected output is 4
print(result)
← Back to All Questions