英文:
Why don't Java for loops work the same way?
问题
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;
}
英文:
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.
答案1
得分: 3
这一行将为你计算索引:
for(int i = 0; i < digits.length; i++)
而你必须通过查找来获取实际数字:
int digit = digits[i];
n = n*10+digit;
而这个表达式将直接为你提供感兴趣的数字:
for(int digit : digits) {
所以你不需要查找,而是直接使用它:
n = n*10+digit;
英文:
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;
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论