![](/img/trans.png)
[英]Java Loop question about !scanner.nextLine() as condition
[英]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
,但該值將在下一行中使用。
比方說, carry
是1
而digits[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
計算一次,然后只能從中讀取,因此carry
和digits
不再相互依賴。 反過來,你會得到你期望的結果。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.