繁体   English   中英

java中for循环条件的一个问题

[英]A question about for-loop condition in java

我正在解决以下问题:给定一个表示非负整数的非空数字数组,加上整数。 例如:[1,2,3] 输出:[1,2,4] 我的方法是使用进位来计算从结束到开始的单数。 我得到了这个问题的 2 个版本。 当输入为 [1,4,4,9] 时,第一个不起作用。但是,第二个是工作。 在第二个版本中,我更改了 for 循环条件。 我想知道为什么会这样? 有人可以帮我解决这个问题吗? 任何帮助,将不胜感激! 谢谢! 版本 1:

   public static int[] plusOne(int[] digits) {
        int sum = 0;
        int len = digits.length;
        int carry = (digits[digits.length -1]+1)/10;
        digits[digits.length -1] = (digits[digits.length -1]+1)%10;

        for (int j = len-2;j >= 0;j--){

            carry = (digits[j]+carry)/10 ;
            digits[j] =(digits[j]+carry)%10 ;
        }

        if (carry==0) return digits;
        else{
            int[] res = new int[len+1];
            res[0] = 1;
            int i = 0;
            for (int j=1;j<res.length;j++){
                res[j] = digits [i++];
            }
            return res;
        }
    }

版本 2:

public static int[] plusOne(int[] digits) {
        int sum = 0;
        int len = digits.length;
        int carry = (digits[digits.length -1]+1)/10;
        digits[digits.length -1] = (digits[digits.length -1]+1)%10;

        for (int j = len-2;j >= 0;j--){
        int temp = digits[j]+carry;
        carry = (temp)/10 ;
        digits[j] =(temp)%10 ;
        }

        if (carry==0) return digits;
        else{
            int[] res = new int[len+1];
            res[0] = 1;
            int i = 0;
            for (int j=1;j<res.length;j++){
                res[j] = digits [i++];
            }
            return res;
        }

毕竟发布更长的答案......

这两个代码片段的唯一区别是第一个for循环。 您的第一个示例没有按预期工作。

for (int j = len-2;j >= 0;j--){
        carry = (digits[j]+carry)/10 ;
        digits[j] =(digits[j]+carry)%10 ;
}

这里的问题在于行进carry = (digits[j]+carry)/10 ;
您正在更改变量carry ,但该值将在下一行中使用。

比方说, carry1digits[j]5 carry = (digits[j]+carry)/10;carry = (digits[j]+carry)/10; 变量carry更改为0并且随后的digits[j]计算结果为5而不是6

第二个示例有效,因为您要引入一个中间变量temp

for (int j = len-2;j >= 0;j--){
    int temp = digits[j]+carry;
    carry = (temp)/10 ;
    digits[j] =(temp)%10 ;
}

temp计算一次,然后只能从中读取,因此carrydigits不再相互依赖。 反过来,你会得到你期望的结果。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM