[LeetCode] Add two numbers

本題相對簡單,CC上有個反過來的比較蛋疼, 這個順着的比較好寫。
這個版本寫的比較長一點,但邏輯一目瞭然:先加兩個list共同長度的部分,再把較長的加上去,最後還要check有木有進位。

/**
 * 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) {
      if (l1 == null){
         return l2;
      }
      if (l2 == null){
         return l1;
      }
      int i = 0, j = 0;
      ListNode current = null;
      ListNode head = null;
      for (;l1 != null && l2 != null; l1 = l1.next, l2 = l2.next){
         int sum = l1.val + l2.val + j;
         i = sum % 10;
         j = sum / 10;
         ListNode s = new ListNode(i);
         if (head == null){
            head = s;
         } else {
            current.next = s;
         }
            current = s;
         }
         ListNode t = (l1 != null)? l1 : l2;
         for (; t != null; t = t.next){
            int sum = t.val + j;
            i = sum % 10;
            j = sum / 10;
            ListNode s = new ListNode(i);
            current.next = s;
            current = s;
         }
         if (j > 0){
            ListNode s = new ListNode(j);
            current.next = s;
            current = s;
         }
         return head;
      } //end of for loop
   <span style="font-family: Arial, Helvetica, sans-serif;">} //end of method</span>
<span style="font-family: Arial, Helvetica, sans-serif;">}//end of class</span>



如果把上面的縮短一點,就變成這樣: (如果一個list是空的,一下解法有點浪費)

public class Solution { 
   public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
      int i = 0, j = 0;
      ListNode current = null;
      ListNode head = null;
      for (;l1 != null || l2 != null || j > 0; l1 = (l1 == null) ? null : l1.next, l2 = (l2 == null) ? null : l2.next){
         int v1 = (l1 == null) ? 0 : l1.val;int v2 = (l2 == null) ? 0 : l2.val;
	     int sum = v1 + v2 + j;
	     i = sum % 10;
	     j = sum / 10;
	     ListNode s = new ListNode(i);
	     if (head == null){
     	    head = s;
	     } else {
    	    current.next = s;
         }
         current = s;
      } 
      return head; 
   }
}


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