[leedcode 02] Add Two Numbers

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

 

此题有几点需要注意:

两表不等长情况;

最后一位进位的处理:

/**
 * 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) {
        ListNode a=l1;
        ListNode b=l2;
        ListNode newHead=new ListNode(-1);
        ListNode c=newHead;
        int index=0;
        while(a!=null||b!=null){
            int n1=a==null?0:a.val;//此处判断的技巧,需要考虑两个表不等长情况
            int n2=b==null?0:b.val;
            int temp=n1+n2+index;
             index=temp/10;
            ListNode node=new ListNode(temp%10);
            c.next=node;
            c=node;
            a=a==null?null:a.next;//注意此处的判断
            b=b==null?null:b.next;
  
        }
        if(index!=0){//注意此处对最后进位的处理
        ListNode node=new ListNode(index);
        c.next=node; 
        }
        return newHead.next;
        
    }
}

 

posted @ 2015-07-03 23:46  ~每天进步一点点~  阅读(151)  评论(0编辑  收藏  举报