1. 程式人生 > >LeetCode-2. Add Two Numbers

LeetCode-2. 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.

這個題目有點像LeetCode的415題字串相加那題,不過這題是基於連結串列的所以得迴圈一下求得這個數的長度不像字串那麼方便

其他的話基本是一樣的

solution

class Solution {
    
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode root = null; //定義根結點
        ListNode tail = null; //定義尾結點
        int jin = 0;   //進位標誌
        ListNode a = l1;
        ListNode b = l2;
        int lena = 1;
        int lenb = 1;
        while(a.next!=null){   //求l1的節點數注意不能直接用l1否則後面l1就不是頭結點了
            lena ++;
            a = a.next;
        }
        while(b.next!=null){   //求l2的節點數
            lenb ++;
            b = b.next;
        }
        
        while(lena>=0||lenb>=0){  //迴圈相加
            int i1,i2;
            if(l1 == null)i1=0;  //這裡有個技巧因為我們不判斷l1和l2誰長所以如果誰是空了加0就好
            else i1=l1.val;
            if(l2 == null)i2=0;
            else i2=l2.val;
            
            if(l1==null&&l2==null){ //如果l1和l2都是空了那很顯然這個運算已經結束了break出去
                if(jin==1) //這裡注意如果l1和l2都空了但是進位標誌為1那麼tail後面還要插入一個值為1的結點
                    tail.next = new ListNode(1);
                break;
            }
                
            int n = i1 + i2 +jin;
            if(jin==1)
                jin=0;
            if(n>=10){
                n-=10;
                jin+=1;
            }
            
            if(root==null){ 
                ListNode t = new ListNode(n);
                root = t;
                tail = t;
            }
            else{
                ListNode t = new ListNode(n);
                tail.next = t;
                tail = tail.next;
            }
            if(l1 != null)l1 = l1.next;  //l1和l2往後一個結點如果其等於空就不需要操作了
            if(l2 != null)l2 = l2.next;
            lena--;  //l1的長度和l2的長度作為判斷條件迴圈一次後各減去1
            lenb--;
        }
        return root;
    }
}