Given a positive integer n
, return the alternating sum of its digits starting from the leftmost digit. The alternating sum of a number is defined as:
n = 521
Output: 5 - 2 + 1 = 4
n = 111
Output: 1 - 1 + 1 = 1
n
? (Assuming it is a positive integer and fits within standard integer limits.)For the sake of simplicity, let’s assume n
is a positive integer with no leading zeros.
n
to its string representation to easily access each digit.alternating_sum = 0
).alternating_sum
.def alternatingDigitSum(n: int) -> int:
n_str = str(n)
alternating_sum = 0
# Iterate over the digits and apply the alternating sum logic
for idx, digit in enumerate(n_str):
digit = int(digit)
if idx % 2 == 0:
alternating_sum += digit
else:
alternating_sum -= digit
return alternating_sum
# Example usage
print(alternatingDigitSum(521)) # Output: 4
print(alternatingDigitSum(111)) # Output: 1
The time complexity of this algorithm is O(d), where d
is the number of digits in the integer n
. This is because we are iterating over each digit exactly once. The conversion from integer to string and integer parsing operations inside the loop are all O(1)
operations for each digit.
The space complexity is O(1), as we are using a constant amount of space irrespective of the input size. The string representation of n
and the integer sum variable don’t scale with input size in a way that affects asymptotic complexity.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?