jeudi 17 août 2017

Code after if block inside a for loop doesn't work

I'm new to java. This is a question about if block in a for loop. The code is from an algorithm practice here.

    public static int[] plusOne(int[] digits) {

    int size = digits.length;
    for(int i=size-1; i>=0; i--) {
        if(digits[i] < 9) {
            System.out.println("tag1 digits.i = " + digits[i]);
            digits[i]++;
            System.out.println("tag2 digits.i = " + digits[i]);
            return digits;
        }

        System.out.println("tag3 digits.i= " + digits[i]);
        digits[i] = 0; //?
        System.out.println("tag4 digits.i= " + digits[i]);
    }

    int[] intOut = new int [size+1];
    intOut[0] = 1;
    return intOut;
}

In the codes above, I added some println() to show how digit[i] changes.

When the input is {1,2,3}, why the line of digits[i] = 0 doesnt work? Reading the code I thought all int in int[] digits will be set to 0. If it return digits in the if block, will it ignore the rest code in the for loop after the if block?

Aucun commentaire:

Enregistrer un commentaire