leetcode 2. Add Two Numbers [java]

Posted why

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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;
    }

以上是关于leetcode 2. Add Two Numbers [java]的主要内容,如果未能解决你的问题,请参考以下文章

2. 两个数相加 [leetcode 2: Add Two Numbers]

2. 两个数相加 [leetcode 2: Add Two Numbers]

LeetCode - 2 - Add Two Numbers

[leetcode][2] Add Two Numbers

[LeetCode]2. Add Two Numbers

LeetCode - 2. Add Two Numbers