I am working on a piece of C# code that is adding digits that are stored in singly linked list. I have created a buffer singly linked list that contains 11 11 8 . the final list has to look like 1 2 9 . Each element that is bigger than 10 has to pass a carry over to the next digit and the result of the %10 is passed to the final list that will create 1 2 9.
How can I handle the carry over from each digit starting on the left to the right?
I have created the following logic, but obviously I am ignoring something.
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);
It doesn’t look like you’re carrying anything over from one value to the next. Also, you’re adding to both ends of the output list, which seems suspect.
Here’s an implementation for a simple
List<int>– it basically does what you do when you add two numbers by hand, just without actually adding. Take the current number, add the carried number, store the “units”, carry the “tens” over to the next column.You should be able to modify it for a linked list (
[i] -> .GetValue(i),.Add -> .InsertAtTail,.Count -> .Size()or similar):