Topic Tags: Linked List, Math
Topic gave us two Linked List, each represents a number, but the opposite order. Let's add two numbers.
And general added almost the same, but turned into a Linked List, or to use / and%, specifically to see the code.
Java Solution:
Runtime: 2ms, faster than 87%
Memory Usage: 44MB, less than 85%
Completion Date: 07/05/2019
Key point: use / get carry;% made use of the remainder
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ class Solution { public ListNode addTwoNumbers(ListNode l1, ListNode l2) { ListNode dummyHead = new ListNode(0); ListNode cursor1 = l1; ListNode cursor2 = l2; ListNode cursor3 = dummyHead; int carry = 0; while(cursor1 != null || cursor2 != null) // go through both list { // if node exists, get the value, elsewise, default 0 int num1 = 0; int num2 = 0; if(cursor1 != null) num1 = cursor1.val; if(cursor2 != null) num2 = cursor2.val; int sum = num1 + num2 + carry; // update carry and sum carry = sum / 10; cursor3.next = new ListNode(sum % 10); cursor3 = cursor3.next; // move both list to next node if(cursor1 != null) cursor1 = cursor1.next; if(cursor2 != null) cursor2 = cursor2.next; } // at last, still need to check carry for last digit if(carry == 1) cursor3.next = new ListNode(1); return dummyHead.next; } }
LeetCode title list - LeetCode Questions List
Topic Source: https: //leetcode.com/