RenzCutie

Add2Nums

Oct 10th, 2021
62
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.89 KB | None | 0 0
  1. // This solution is shared from APAS. The highest rated coding interview algorithm learning APP on Android! Download it from here: https://goo.gl/YXD3m2
  2. public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
  3.     ListNode dummyHead = new ListNode(0);
  4.     ListNode p = l1, q = l2, curr = dummyHead;
  5.     int carry = 0;
  6.     while (p != null || q != null) {
  7.         int x = (p != null) ? p.val : 0;
  8.         int y = (q != null) ? q.val : 0;
  9.         int sum = carry + x + y;
  10.         carry = sum / 10;
  11.         curr.next = new ListNode(sum % 10);
  12.         curr = curr.next;
  13.         if (p != null) p = p.next;
  14.         if (q != null) q = q.next;
  15.     }
  16.     if (carry > 0) {
  17.         curr.next = new ListNode(carry);
  18.     }
  19.     return dummyHead.next;
  20. }
  21. // This solution is shared from APAS. The highest rated coding interview algorithm learning APP on Android! Download it from here: https://goo.gl/YXD3m2
Advertisement
Add Comment
Please, Sign In to add comment