旅鸟

导航

0002 两数相加

给定两个非空链表来表示两个非负整数。位数按照逆序方式存储,它们的每个节点只存储单个数字。将两数相加返回一个新的链表。

你可以假设除了数字 0 之外,这两个数字都不会以零开头。

示例:

输入:(2 -> 4 -> 3) + (5 -> 6 -> 4)
输出:7 -> 0 -> 8
原因:342 + 465 = 807
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     public int val;
 *     public ListNode next;
 *     public ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    public ListNode AddTwoNumbers(ListNode l1, ListNode l2) {
        ListNode n1 = l1;
        ListNode n2 = l2;
        ListNode res = new ListNode(0);
        ListNode p = res;
        int sum = 0;
        while(n1 != null || n2 != null){
            if(n1 != null && n2 != null){
                sum += n1.val + n2.val;
                n1 = n1.next;
                n2 = n2.next;
            } else if(n1 != null){
                sum += n1.val;
                n1 = n1.next;
            } else if(n2 != null){
                sum += n2.val;
                n2 = n2.next;
            } else {
                break;
            }
            if(sum < 10){
                ListNode node = new ListNode(sum);
                p.next = node;
                p = node;
                sum = 0;
            } else{
                ListNode node = new ListNode(sum-10);
                p.next = node;
                p = node;
                sum = 1;
            }
        }
        if(sum == 1){
            ListNode node = new ListNode(1);
            p.next = node;
            p = node;
        }
        return res.next;
    }
}

 

posted on 2018-07-31 12:58  旅鸟  阅读(142)  评论(0编辑  收藏  举报