Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * Definition for singly-linked list.
- * public class ListNode {
- * int val;
- * ListNode next;
- * ListNode(int x) { val = x; }
- * }
- */
- class Solution {
- public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
- int index = 0;
- int overflow = 0;
- ListNode returnList = null;
- ListNode linkedListPtr = null;
- while (l1 != null && l2 != null) {
- int one = l1.val;
- int two = l2.val;
- int sum = one + two + overflow;
- // Calculate overflow
- overflow = sum / 10;
- sum = sum % 10;
- ListNode curNode = new ListNode(sum);
- if (returnList == null) {
- returnList = curNode;
- linkedListPtr = returnList;
- }
- else {
- linkedListPtr.next = curNode;
- linkedListPtr = linkedListPtr.next;
- }
- l1 = l1.next;
- l2 = l2.next;
- }
- // Add any remaining numbers in l1 and l2
- while (l1 != null) {
- int sum = l1.val + overflow;
- // Calculate overflow
- overflow = sum / 10;
- sum = sum % 10;
- ListNode curNode = new ListNode(sum);
- linkedListPtr.next = curNode;
- linkedListPtr = linkedListPtr.next;
- l1 = l1.next;
- }
- while (l2 != null) {
- int sum = l2.val + overflow;
- // Calculate overflow
- overflow = sum / 10;
- sum = sum % 10;
- ListNode curNode = new ListNode(sum);
- linkedListPtr.next = curNode;
- linkedListPtr = linkedListPtr.next;
- l2 = l2.next;
- }
- // IF overflow is still not 0
- if (overflow != 0) {
- ListNode curNode = new ListNode(overflow);
- linkedListPtr.next = curNode;
- linkedListPtr = linkedListPtr.next;
- overflow = 0;
- }
- return returnList;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement