Similar Problems
Similar Problems not available
Alternating Digit Sum - Leetcode Solution
Companies:
LeetCode: Alternating Digit Sum Leetcode Solution
Difficulty: Easy
Topics: math
Problem Statement:
Given an integer n, return the alternating digit sum of the digits in n, starting with the first digit.
The alternating digit sum of a number is the sum of the digits in even positions minus the sum of the digits in odd positions.
Example:
Input: n = 123456 Output: 1 - 2 + 3 - 4 + 5 - 6 = -3
Solution:
The problem statement is quite simple, the difficult part of the problem is to get the digits that are in the even positions and the digits that are in the odd positions. Below is the high-level approach to solve this problem.
- Get the digits of the number and store them in an array.
- Traverse through the array and keep adding the digits of even position and odd position.
- Subtract the sum of the digits at even position with the sum of the digits at odd positions to get the Alternating Digit Sum.
Let us now dive into code and implement the above approach.
class Solution {
public int sum(int n) {
int[] digits = getDigits(n);
int evenSum = 0, oddSum = 0;
for (int i = 0; i < digits.length; i++) {
if (i % 2 == 0) {
evenSum += digits[i];
} else {
oddSum += digits[i];
}
}
return evenSum - oddSum;
}
public int[] getDigits(int n) {
String str = Integer.toString(n);
int[] digits = new int[str.length()];
for (int i = 0; i < str.length(); i++) {
digits[i] = str.charAt(i) - '0';
}
return digits;
}
}
In the above code, we first defined a method getDigits
that takes an integer, converts it to a String, and then stores the digits in an integer array. Then, in the sum
method, we used the getDigits
method to get all the digits of the number and then calculated the alternating digit sum as per the approach discussed above.
Complexity Analysis:
Time Complexity: O(n) The approach processes each digit in the number once and performs constant-time operations. Therefore, the time complexity of the approach is O(n)
Space Complexity: O(n) The approach creates an array of size n, where n is the number of digits in the number. Therefore, the space complexity of the approach is O(n)
Conclusion:
In this tutorial, we saw the solution to the Alternating Digit Sum problem on Leetcode. We used a simple approach to calculate the alternating digit sum and then implemented the approach in Java.
Alternating Digit Sum Solution Code
1