[刷题]Add Two Numbers

来源:互联网 发布:安徽卫视网络直播 编辑:程序博客网 时间:2024/06/03 16:17

[LintCode]Add Two Numbers

/** * 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) {        // 2015-08-28        if (l1 == null) {            return l2;        }        if (l2 == null) {            return l1;        }                ListNode dummy = new ListNode(0);        ListNode tail = dummy;        int carry = 0; // 进位                while (l1 != null && l2 != null) {            int sum = l1.val + l2.val + carry;            carry = sum / 10;            tail.next = new ListNode(sum % 10);            l1 = l1.next;            l2 = l2.next;            tail = tail.next;        }                while (l1 != null) {            int sum = l1.val + carry;            carry = sum / 10;            tail.next = new ListNode(sum % 10);            l1 = l1.next;            tail = tail.next;        }                while (l2 != null) {            int sum = l2.val + carry;            carry = sum / 10;            tail.next = new ListNode(sum % 10);            l2 = l2.next;            tail = tail.next;        }                if (carry != 0) {            tail.next = new ListNode(carry);        }                return dummy.next;    }}


0 0
原创粉丝点击