Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //If we need to add 2 integers, just reverse them and call them on addTwoNumbers()
- //Similar to 369 Plus One Linked List
- class Solution {
- public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
- ListNode p1 = l1, p2 = l2, ans = new ListNode(0), p = ans;
- int carry = 0;
- while(p1 != null || p2 != null) {
- if(p1 != null) {
- carry += p1.val;
- p1 = p1.next;
- }
- if(p2 != null) {
- carry += p2.val;
- p2 = p2.next;
- }
- p.next = new ListNode(carry % 10);
- p = p.next;
- carry /= 10;
- }
- if(carry > 0) {
- p.next = new ListNode(carry);
- }
- return ans.next;
- }
- }
- /**
- * Definition for singly-linked list.
- * public class ListNode {
- * int val;
- * ListNode next;
- * ListNode(int x) { val = x; }
- * }
- */
Add Comment
Please, Sign In to add comment