[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; 
   }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值