LeetCode 2544: Alternating Digit Sum

Math

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

  1. Initialize a variable sign to 1 (positive).
  2. Initialize a variable result to 0.
  3. Iterate over the digits of the number from left to right.
  4. 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.
  5. 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...