码迷,mamicode.com
首页 > 其他好文 > 详细

2-Add Two Numbers

时间:2018-03-07 00:52:27      阅读:127      评论:0      收藏:0      [点我收藏+]

标签:exp   output   nbsp   public   put   add   span   ret   lis   

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode p=l1,q=l2;
        ListNode head=new ListNode(0);
        ListNode curr=head;
        int carry=0;
        while(p!=null || q!=null)
        {
            int x=(p!=null)?p.val:0;
            int y=(q!=null)?q.val:0;
            int sum=x+y+carry;
            carry=sum/10;
            curr.next=new ListNode(sum%10);
            curr=curr.next;
            if (p!=null) p=p.next;
            if (q!=null) q=q.next;
        }
        if (carry>0)
            curr.next=new ListNode(carry);
        return head.next;
    }

 

2-Add Two Numbers

标签:exp   output   nbsp   public   put   add   span   ret   lis   

原文地址:https://www.cnblogs.com/kingshine007/p/8519670.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!