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;
        
    }
}

 

转载于:https://www.cnblogs.com/qiaomu/p/4620003.html

Logo

开放原子开发者工作坊旨在鼓励更多人参与开源活动,与志同道合的开发者们相互交流开发经验、分享开发心得、获取前沿技术趋势。工作坊有多种形式的开发者活动,如meetup、训练营等,主打技术交流,干货满满,真诚地邀请各位开发者共同参与!

更多推荐