簡體   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