Guest User

Untitled

a guest
Jun 24th, 2018
78
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.89 KB | None | 0 0
  1. //If we need to add 2 integers, just reverse them and call them on addTwoNumbers()
  2. //Similar to 369 Plus One Linked List
  3. class Solution {
  4. public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
  5. ListNode p1 = l1, p2 = l2, ans = new ListNode(0), p = ans;
  6. int carry = 0;
  7. while(p1 != null || p2 != null) {
  8. if(p1 != null) {
  9. carry += p1.val;
  10. p1 = p1.next;
  11. }
  12. if(p2 != null) {
  13. carry += p2.val;
  14. p2 = p2.next;
  15. }
  16. p.next = new ListNode(carry % 10);
  17. p = p.next;
  18. carry /= 10;
  19. }
  20. if(carry > 0) {
  21. p.next = new ListNode(carry);
  22. }
  23. return ans.next;
  24. }
  25. }
  26. /**
  27. * Definition for singly-linked list.
  28. * public class ListNode {
  29. * int val;
  30. * ListNode next;
  31. * ListNode(int x) { val = x; }
  32. * }
  33. */
Add Comment
Please, Sign In to add comment