LeetCode 2544: Alternating Digit Sum
Problem Description
Explanation
To solve this problem, we can iterate over the digits of the given number from left to right. We will keep track of the current sign, starting with positive. For each digit, we will calculate its value with the corresponding sign and update the sign for the next digit based on the sign of the current digit.
Algorithm
- Initialize a variable
sign
to 1 (positive). - Initialize a variable
result
to 0. - Iterate over the digits of the number from left to right.
- For each digit:
- Calculate the value of the digit by multiplying it with the current sign.
- Add this value to the
result
. - Update the sign for the next digit by multiplying the current sign with -1.
- Return the final
result
.
Time Complexity
The time complexity of this algorithm is O(log n), where n is the given number.
Space Complexity
The space complexity of this algorithm is O(1).
Solutions
class Solution {
public int getSum(int n) {
int sign = 1;
int result = 0;
while (n > 0) {
int digit = n % 10;
result += sign * digit;
sign *= -1;
n /= 10;
}
return result;
}
}
Loading editor...