Advertisement
zxzx4zxzx

LeetCode - Add Two Numbers

Mar 22nd, 2019
131
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.13 KB | None | 0 0
  1. /**
  2.  * Definition for singly-linked list.
  3.  * public class ListNode {
  4.  *     int val;
  5.  *     ListNode next;
  6.  *     ListNode(int x) { val = x; }
  7.  * }
  8.  */
  9. class Solution {
  10.     public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
  11.         int index = 0;
  12.         int overflow = 0;
  13.         ListNode returnList = null;
  14.         ListNode linkedListPtr = null;
  15.        
  16.         while (l1 != null && l2 != null) {        
  17.             int one = l1.val;
  18.             int two = l2.val;
  19.            
  20.             int sum = one + two + overflow;
  21.             // Calculate overflow
  22.             overflow = sum / 10;
  23.             sum = sum % 10;
  24.            
  25.             ListNode curNode = new ListNode(sum);
  26.            
  27.             if (returnList == null) {
  28.                 returnList = curNode;
  29.                 linkedListPtr = returnList;
  30.             }
  31.             else {
  32.                 linkedListPtr.next = curNode;
  33.                 linkedListPtr = linkedListPtr.next;
  34.             }
  35.            
  36.             l1 = l1.next;
  37.             l2 = l2.next;
  38.         }
  39.        
  40.         // Add any remaining numbers in l1 and l2
  41.         while (l1 != null) {
  42.             int sum = l1.val + overflow;
  43.             // Calculate overflow
  44.             overflow = sum / 10;
  45.             sum = sum % 10;
  46.             ListNode curNode = new ListNode(sum);
  47.             linkedListPtr.next = curNode;
  48.             linkedListPtr = linkedListPtr.next;
  49.             l1 = l1.next;
  50.         }
  51.        
  52.         while (l2 != null) {
  53.             int sum = l2.val + overflow;
  54.             // Calculate overflow
  55.             overflow = sum / 10;
  56.             sum = sum % 10;
  57.             ListNode curNode = new ListNode(sum);
  58.             linkedListPtr.next = curNode;
  59.             linkedListPtr = linkedListPtr.next;
  60.             l2 = l2.next;
  61.         }
  62.        
  63.         // IF overflow is still not 0
  64.         if (overflow != 0) {
  65.             ListNode curNode = new ListNode(overflow);
  66.             linkedListPtr.next = curNode;
  67.             linkedListPtr = linkedListPtr.next;
  68.                
  69.             overflow = 0;
  70.         }
  71.        
  72.         return returnList;
  73.     }
  74. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement