为什么Java的for循环工作方式不同呢?

huangapple go评论142阅读模式
英文:

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 &lt; 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 &lt; 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;

huangapple
  • 本文由 发表于 2023年3月9日 14:33:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/75681155.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定