#144 Incrementing an Array of Digits
Write a method that accepts an integer array and adds 1 to the last element. If the last element is 9, write 0 and carry 1 to the previous element, and so on.
import java.util.Arrays;
public class Main {
public static int[] incrementArray(int[] digits) {
return digits;
}
public static void main(String[] args) {
int[] arr1 = {1, 2, 3};
int[] arr2 = {9};
int[] arr3 = {1, 2, 9};
System.out.println(Arrays.toString(incrementArray(arr1))); // [1, 2, 4]
System.out.println(Arrays.toString(incrementArray(arr2))); // [1, 0]
System.out.println(Arrays.toString(incrementArray(arr3))); // [1, 3, 0]
}
}
Question review
Sign in to start the dialogue
The mentor keeps the context of the current question and your previous messages.
Sign in
Available with Premium
This is just one of the solutions available with Premium. And more:
- 250+ advanced lectures
- 1300+ practice exercises
- 500+ solutions to problems from real interviews
- Personalized Java Hub certificates
- Expanded access to the AI mentor