LeetCode 148 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;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        //check para
        if(l1==null || l2==null)
            return null;
        
        ListNode head = new ListNode(0);
        ListNode tail = head;
        int a,b,res,digit;
        int carry = 0;
        while(l1 != null || l2 !=null){
            
            if(l1 == null){
                a = 0; b = l2.val;
                l2 = l2.next;
            }else if(l2 == null){
                a = l1.val; b = 0;
                l1 = l1.next;
            }else{
                a= l1.val; b = l2.val;
                l1 = l1.next;
                l2 = l2.next;
            }
            res = a+b+carry;
            digit = res%10;
            carry = res/10;
            tail.next = new ListNode(digit);
            tail = tail.next;
        }
        if(carry != 0)
            tail.next = new ListNode(carry);
        return head.next;
    }
}


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