#include <iostream>
//Definition for singly-linked list.
struct ListNode {
int val;
ListNode *next;
ListNode() : val(0), next(nullptr) {}
ListNode(int x) : val(x), next(nullptr) {}
ListNode(int x, ListNode *next) : val(x), next(next) {}
};
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2)
{
ListNode *final_ll;
ListNode **ptr_final = &final_ll;
int carry, sum;
while (l1!=NULL || l2!=NULL || carry > 0)
{
int s1 = ((l1!=NULL) ? l1->val: 0);
int s2 = ((l2!=NULL) ? l2->val: 0);
sum = s1 + s2 + carry;
carry = sum / 10;
(*ptr_final) = new ListNode(sum % 10);
//std::cout << "tenth_digit = " << carry << std::endl;
std::cout << "unit_digit = " << sum % 10 << std::endl;
if (l1!=NULL) l1 = l1->next;
if (l2!=NULL) l2 = l2->next;
ptr_final = &((*ptr_final)->next);
}
return final_ll;
}
};
int main() {
ListNode l1(9);
ListNode l2(8, &l1);
ListNode *result = Solution().addTwoNumbers(&l1, &l2);
}
This code outputs:
unit_digit = 5
unit_digit = 1
unit_digit = 1
However, when I uncomment
std::cout << "tenth_digit = " << carry << std::endl;
In Solution
class, outputs are changed to:
tenth_digit = 3278
unit_digit = 4
tenth_digit = 328
unit_digit = 7
tenth_digit = 32
unit_digit = 8
tenth_digit = 3
unit_digit = 2
tenth_digit = 0
unit_digit = 3
A single printing statement should not change the number of iterations of the while loop and the value of unit_digit
during each iteration. What's happening here?