leetcode—Add Two Numbers

You are given two non-empty linked lists representing two non-negative integers. 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.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
Example
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.

class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        if(l1==null && l2==null) return null;
        if(l1==null) return l2;
        if(l2==null) return l1;
        ListNode head = new ListNode(0);
        ListNode cur = head;
        int sum = 0;
        while(l1!=null || l2!=null){
            if(l1!=null){
                sum += l1.val;
                l1 = l1.next;
            }
            if(l2!=null){
                sum += l2.val;
                l2 = l2.next;            
            }
            cur.next = new ListNode(sum%10);
            cur = cur.next;
            sum = sum/10;
        }
        if(sum==1) cur.next = new ListNode(1);
        return head.next;
    }
}

這裏是通過利用一個臨時變量,存儲兩個整數對應分位上的值相加,利用這個sum對10求餘就是當前結果對應位上的值,然後這兩個整數分別賦值爲自己的下一位,而sum呢?則除以10,若有進位則sum爲1,在下一位兩個整數相加時,加上這個1,while終止的條件是兩個鏈表都爲空,這裏注意頭節點怎麼處理的問題

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章