algoadvance

Leetcode 2544. Alternating Digit Sum

Problem Statement

You are given a positive integer n. Each digit of n has a sign according to its position:

You need to return the sum of all digits with their corresponding sign.

Clarifying Questions

  1. Input Size: What is the maximum value of n? (This will help determine if we need to consider integer overflow or not)
  2. Output: Should we verify that n is always a positive integer greater than 0 and contains only digits?

Assuming reasonable constraints, we will proceed.

Example

For example, if n = 521, the result should be 5 - 2 + 1 = 4.

Strategy

  1. Initialization: Track the sum by initializing a variable, say sum, to 0.
  2. Iteration: Convert the number to a string to access each digit’s position easily.
  3. Sign Determination: Iterate over each character in the string representation of the number:
    • If the position is odd (0-indexed even), add the digit to the sum.
    • If the position is even (0-indexed odd), subtract the digit from the sum.
  4. Result: Return the final value of the sum.

Code

Here’s the Java implementation to solve the problem:

public class AlternatingDigitSum {
    public static int alternateDigitSum(int n) {
        String s = Integer.toString(n);
        int sum = 0;
        for (int i = 0; i < s.length(); i++) {
            int digit = Character.getNumericValue(s.charAt(i));
            if (i % 2 == 0) {
                // Odd position (1-based)
                sum += digit;
            } else {
                // Even position (1-based)
                sum -= digit;
            }
        }
        return sum;
    }

    // Example usage
    public static void main(String[] args) {
        int n = 521;
        System.out.println("Alternating Digit Sum of " + n + " is: " + alternateDigitSum(n)); // Output: 4
    }
}

Time Complexity

This solution efficiently calculates the alternating digit sum based on given constraints.

Cut your prep time in half and DOMINATE your interview with AlgoAdvance AI