2012-11-27 23 views
0

我正在研究一段C#代碼,它添加了存儲在單獨鏈接列表中的數字。我創建了一個包含11 11 8的緩衝單鏈表。最終的名單必須看起來像1 2 9。每個大於10的元素必須將餘數傳遞給下一個數字,並將%10的結果傳遞給將創建1 2的最終列表。 如何處理從每個數字開始的結轉從左到右?添加號碼時如何處理遺留物?

我已經創建了以下邏輯,但顯然我忽略了某些東西。

for (int i = 0; i < bufferList.Size(); i++) 
{ 
    int mostLeftValue = Convert.ToInt32(bufferList.GetValue(i)); 
    if (mostLeftValue >=10 && i + 1 < bufferList.Size()) 
    { 
     int nextLeftValue = Convert.ToInt32(bufferList.GetValue(i + 1))+1; 
     int modedNextValue = nextLeftValue % 10; 
     finalList.InsertAtTail(modedNextValue);   
    } 

    int moddedValue = mostLeftValue %10 ; 
    finalList.InsertAtFront(moddedValue); 

回答

1

它看起來並不像你從一個值到下一個承載什麼結束。此外,您正在添加到輸出列表的兩端,這似乎是可疑的。

下面是一個簡單的List<int>實現 - 它基本上做你做什麼時,你手工添加兩個數字,只是沒有實際添加。取現在的號碼,加上攜帶的號碼,存儲「單位」,將「十」號攜帶到下一列。

Number  11 11 8 
Carry  0 ┌─ 1 ┌─ 1 ┌─ 0 
Sum   11 │ 12 │ 9 │ 
Store  1 │ 2 │ 9 │ stop 
Carry over 1 ─┘ 1 ─┘ 0 ─┘ 

你應該能夠修改它鏈表([i] -> .GetValue(i).Add -> .InsertAtTail.Count -> .Size()或類似):

int carry = 0; 
for (int i = 0; i < input.Count; i++) 
{ 
    int sum = carry + input[i]; // add previous carry 
    output.Add(sum % 10);  // store the "units" 
    carry = sum/10;   // carry the "tens" 
} 
while (carry > 0)    // anything left carried? 
{ 
    output.Add(carry % 10);  // store the "units" 
    carry = carry/10;   // carry the "tens" 
} 
+0

你的邏輯工作,謝謝。 – user843681