Leetcode 2544. Alternating Digit Sum
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.
n
? (This will help determine if we need to consider integer overflow or not)n
is always a positive integer greater than 0 and contains only digits?Assuming reasonable constraints, we will proceed.
For example, if n = 521
, the result should be 5 - 2 + 1 = 4
.
sum
, to 0.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
}
}
O(d)
, where d
is the number of digits in n
. This is because we iterate over each digit exactly once.O(1)
if we ignore the space used for the input string conversion and the result storage. If we consider the input string, it will be O(d)
.This solution efficiently calculates the alternating digit sum based on given constraints.
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?