望着时间滴答滴答的流过,我不曾改变过 . . .

leetcode 2. Add Two Numbers [java]

注意点:

  1. 最后的进位
  2. (l1 == null || l1.next == null)
  3. break;
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        boolean j = false;
        ListNode p = new ListNode(0);
        ListNode res = p;
        while(true){
            int a = (l1 != null ? l1.val : 0) + (l2 != null ? l2.val : 0) + (j ? 1 : 0); 
            if(a >= 10){
                j = true;
                p.val = a - 10;
            }else{
                j = false;
                p.val = a;
            }
            
            l1 = (l1 == null || l1.next == null) ? null : l1.next;
            l2 = (l2 == null || l2.next == null) ? null : l2.next;
            boolean ok = l1 == null && l2 == null;
            if(! ok){
                p.next = new ListNode(0);
                p = p.next;    
            }else
                break;
        }
        if(j)
            p.next = new ListNode(1);
        return res;
    }
posted @ 2019-04-04 19:45  whyaza  阅读(99)  评论(0编辑  收藏  举报