add-two-numbers

来源:互联网 发布:数据库not null 编辑:程序博客网 时间:2024/06/05 18:34

Easy Add Two Numbers

23%
Accepted

You have two numbers represented by a linked list, where each node contains a single digit. The digits are stored in reverse order, such that the 1's digit is at the head of the list. Write a function that adds the two numbers and returns the sum as a linked list.

Have you met this question in a real interview? 
Yes
Example

Given 7->1->6 + 5->9->2. That is, 617 + 295.

Return 2->1->9. That is 912.

Given 3->1->5 and 5->9->2, return 8->0->8.

Tags Expand 
Cracking The Coding Interview Linked List High Precision

/** * Definition for singly-linked list. * public class ListNode { *     int val; *     ListNode next; *     ListNode(int x) { *         val = x; *         next = null;       *     } * } */public class Solution {    /**     * @param l1: the first list     * @param l2: the second list     * @return: the sum list of l1 and l2      */    public ListNode addLists(ListNode l1, ListNode l2) {        if(l1 == null && l2 == null){            return null;        }        ListNode dummy = new ListNode(0);        ListNode point = dummy;        int carry = 0;        while(l1 != null && l2 != null){            int sum = carry + l1.val + l2.val;            point.next = new ListNode(sum%10);            carry = sum / 10;            l1 = l1.next;            l2 = l2.next;            point = point.next;        }        while(l1 != null){            int sum = carry + l1.val;            point.next = new ListNode(sum%10);            carry = sum / 10;            l1 = l1.next;            point = point.next;        }        while(l2 != null){            int sum = carry + l2.val;            point.next = new ListNode(sum%10);            carry = sum / 10;            l2 = l2.next;            point = point.next;        }        if(carry != 0){            point.next = new ListNode(carry);            point = point.next;        }        return dummy.next;    }}


0 0