Leetcode–Add Two Numbers

The Problem:

You are given two linked lists representing two non-negative numbers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8

 

Notes:

  1. Be careful don’t forget the last carry when all nodes traversed, should add one more node for carry.

Java Solution:

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode fkHead = new ListNode(0);
        ListNode pre = fkHead;
        int carry = 0;
        while(l1!=null && l2!= null){
            ListNode p = new ListNode((l1.val+l2.val+carry)%10);
            carry = (l1.val+l2.val+carry)/10;
            pre.next = p;
            pre = p;
            l1 = l1.next;
            l2 = l2.next;
        }
        while(l1!= null){
            ListNode p = new ListNode((l1.val+carry)%10);
            carry = (l1.val+carry)/10;
            pre.next = p;
            pre = p;
            l1 = l1.next;
        }
        while(l2!= null){
            ListNode p = new ListNode((l2.val+carry)%10);
            carry = (l2.val+carry)/10;
            pre.next = p;
            pre = p;
            l2 = l2.next;
        }
        if(carry!=0){ //---!!!---don't forget the last carry when nodes all finished
            ListNode p = new ListNode(carry);
            pre.next = p;
        }
        return fkHead.next;
    }
}
Advertisements

One thought on “Leetcode–Add Two Numbers

  1. Pingback: Leetcode–Add Binary | Linchi is coding

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s