-1
public static int[] plusOne(int[] digits) {
   long n = 0;
   for(int i = 0; i < digits.length; i++) {
     n = n*10+digits[i];
   }
   System.out.println(n);
   n = 0; 
   for(int i : digits) {
     n = n*10+digits[i];
   }
   System.out.println(n);
   return digits;
}

The above code for me prints entirely different numbers for n depending on which loop I use. The first one prints out "9876543210" and the second one prints out "123456789". My input array is "{9,8,7,6,5,4,3,2,1,0}." I am changing the int[] array to a single value and expected output is the result of the classic for loop "9876543210". My understanding is that these should work essentially the same way.

himan01
  • 1
  • 2
  • 5
    The second loop should use `i` instead of `digits[i]`. – tkausl Mar 09 '23 at 06:35
  • inside the first loop you are iterating through the index, inside the second loop you are iterating through the objects in this case an integer – Icarus Mar 09 '23 at 06:37
  • Because ... there's a bug / typo in your code ... as explained by other comments and the answer. Basically, code does what you tell it. But in this case you told it to do different things. (Aside: I recommend the [Rubber Duck Debugging](https://rubberduckdebugging.com) technique as a good way to spot this kind of error. And as a good self-training technique.) – Stephen C Mar 09 '23 at 06:52
  • 1
    in the first loop, i is the index, in the second it's the element of the array – Stultuske Mar 09 '23 at 06:55

1 Answers1

3

This line will count indexes for you:

for(int i = 0; i < digits.length; i++)

and you have to get to the real number by looking it up:

int digit = digits[i];
n = n*10+digit;

While that expression will directly give you the numbers you are interested in:

for(int digit : digits) {

so you do not look up but use it directly:

n = n*10+digit;
Queeg
  • 7,748
  • 1
  • 16
  • 42