leetcode第二題AddTwoNumber

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.
給定兩個非空的鏈表,表示兩個非負整數。 數字以相反的順序存儲,每個節點包含一個數字。 添加兩個數字並將其作爲鏈表返回。
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8

emmm,就是鏈表對應的相加,有進位的進位到下一個相加的節點,null的當做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) {
         ListNode shit = new ListNode(0);
        ListNode temp  =shit;
        ListNode a = l1;
        ListNode b = l2;
        int carry = 0;//表示進位符號
        while (a!=null||b!=null)
        {
            //如果有個鏈表短,則空的就當做0,
            int first = (a==null)?0:a.val;
            int second = (b==null)?0:b.val;
            int sum = first+second+carry;
            carry = sum/10;
            temp.next = new ListNode(sum%10);
            temp = temp.next;
            if(a!=null)a = a.next;
            if(b!=null)b = b.next;
        }
        if(carry>0){//這裏如果到了最後一位加還有一個進位的時候要多加一個節點
            temp.next = new ListNode(carry);
        }
        return shit.next;
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章