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

Leetcode2 Add Two Numbers

时间:2015-04-08 21:15:14      阅读:107      评论:0      收藏:0      [点我收藏+]

标签:

描述:

You are given two linked lists representing two non-negative numbers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 –> 8

本来想法(最笨的想法)是把两个链表都读出来组成数字,反转相加,再将二者的和反转存到一个链表,经谷歌提点,本来两个链表就是从个位开始的,一位一位相加,进位在下个高位继续加。

public class Solution {
    public static ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode head = new ListNode(0);    // empty header;
        ListNode resCur = head;
        ListNode cursor1 = l1;
        ListNode cursor2 = l2;

        int remad=0;
        int m=0;
        while(cursor1!=null || cursor2!=null){
            int sum=0;
            int val1=0;
            int val2=0;
            if(cursor1!=null){
                val1=cursor1.val;
            }
            if(cursor2!=null){
                val2=cursor2.val;
            }
            sum=val1+val2+remad;
            remad=sum/10;
            m=sum%10;
            resCur.next=new ListNode(m);
            resCur=resCur.next;
            if(cursor1!=null)
                cursor1=cursor1.next;
            if(cursor2!=null)
                cursor2=cursor2.next;
        }
        if(remad!=0)
            resCur.next=new ListNode(remad);
        return head.next;
    }
    public static  void main(String[] args){
        ListNode l1=new ListNode(5);
        l1.next=new ListNode(4);

        ListNode l2=new ListNode(5);
        l2.next=new ListNode(5);

        ListNode resNum=new ListNode(0);
        resNum=addTwoNumbers(l1,l2);
        while (resNum!=null){
            System.out.print(resNum.val+"->");
            resNum=resNum.next;
        }
    }
}

Leetcode2 Add Two Numbers

标签:

原文地址:http://www.cnblogs.com/duanqiong/p/4403570.html

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