#144 Incrementing an Array of Digits

Companies:
Sberbank
Themes:
AlgorithmsArraysPractice

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

Mentor
Answer as you would in a real interview. I’ll ask follow-up questions, then compare your answer with the reference answer and show your accuracy as a %.
Sign in to start the dialogue The mentor keeps the context of the current question and your previous messages.
Sign in