Advertisement
1988coder

2. Add Two Numbers

Jan 6th, 2019
101
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.14 KB | None | 0 0
  1. // LeetCode URL: https://leetcode.com/problems/add-two-numbers/
  2.  
  3. //   Definition for singly-linked list.
  4. class ListNode {
  5.     int val;
  6.     ListNode next;
  7.  
  8.     ListNode(int x) {
  9.         val = x;
  10.     }
  11. }
  12.  
  13. /**
  14.  * Time Complexity: O(max(M, N))
  15.  *
  16.  * Space Complexity: O(1)
  17.  *
  18.  * M = Length of list l1. N = Length of list l2
  19.  */
  20. class Solution {
  21.     public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
  22.         if (l1 == null) {
  23.             return l2;
  24.         }
  25.         if (l2 == null) {
  26.             return l1;
  27.         }
  28.  
  29.         ListNode dummyHead = new ListNode(-1);
  30.         ListNode curr = dummyHead;
  31.         ListNode p = l1;
  32.         ListNode q = l2;
  33.         int carry = 0;
  34.  
  35.         while (p != null || q != null || carry > 0) {
  36.             int sum = carry;
  37.             if (p != null) {
  38.                 sum += p.val;
  39.                 p = p.next;
  40.             }
  41.             if (q != null) {
  42.                 sum += q.val;
  43.                 q = q.next;
  44.             }
  45.             curr.next = new ListNode(sum % 10);
  46.             carry = sum / 10;
  47.             curr = curr.next;
  48.         }
  49.  
  50.         return dummyHead.next;
  51.     }
  52. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement