首页 > 其他 > 详细

2. Add Two Numbers

时间:2016-08-09 20:18:23      阅读:242      评论:0      收藏:0      [点我收藏+]
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        //利用先求得整数int结果的方法会造成溢出的错误
        int isOver=0;
        ListNode t1=l1;
        ListNode t2=l2;
        ListNode head=null;
        ListNode last=null;
        while(t1!=null&&t2!=null)
        {
            int temp=t1.val+t2.val+isOver;
            if(temp>=10)
                isOver=1;
            else
                isOver=0;
            ListNode t=new ListNode(temp%10);
            if(head==null)
                head=t;
            if(last!=null)
                last.next=t;
            last=t;
            t1=t1.next;
            t2=t2.next;
        }
        while(t1!=null)
        {
            int temp=t1.val+isOver;
            if(temp>=10)
                isOver=1;
            else
                isOver=0;
            ListNode t=new ListNode(temp%10);
            if(head==null)
                head=t;
            if(last!=null)
                last.next=t;
            last=t;
            t1=t1.next;
        }
        while(t2!=null)
        {
            int temp=t2.val+isOver;
            if(temp>=10)
                isOver=1;
            else
                isOver=0;
            ListNode t=new ListNode(temp%10);
            if(head==null)
                head=t;
            if(last!=null)
                last.next=t;
            last=t;
            t2=t2.next;
        }
        if(t1==null&&t2==null&&isOver==1)
        {
            ListNode t=new ListNode(1);
            if(head==null)
                head=t;
            if(last!=null)
                last.next=t;
            last=t;
        }
        return head;
    }
}

 

2. Add Two Numbers

原文:http://www.cnblogs.com/aguai1992/p/5754331.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!