https://leetcode.com/problems/add-two-numbers/description/
Question:
You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
Example:
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Hint:
https://leetcode.com/problems/add-two-numbers/solution/
Keep track of the carry using a variable and simulate digits-by-digits sum starting from the head of list, which contains the least-significant digit.
My Solution:
Note:
1. "new" the head of our list
ListNode list_head = new ListNode(0);
2. "current" to the head of our list
ListNode list_current = list_head;
3. key point is to define "carry"
int overload =0; //carry
4. need to add overload(carry)
sum = a_digit + b_digit + overload;
5. important: the special case, when a and b are both null, and there is an overload
if(overload ==1){
list_current.next = new ListNode(1); //"new" the next node with "1"
list_current = list_current.next; //"current" to the next node
}
No comments:
Post a Comment