2. 兩數相加

五十五号列车發表於2024-07-24
class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
       ListNode curr = new ListNode(0);
        ListNode head = curr;
        int plus =0;
        while (l1 != null || l2!=null || plus !=0){
            int a = l1==null?0:l1.val;
            int b = l2==null?0:l2.val;
            int res  = (a + b + plus)%10;
            plus  = (a+ b +plus)/10;
            curr.next = new ListNode(res);
            curr = curr.next;
            if(l1 != null) l1 = l1.next;
            if(l2 != null) l2 = l2.next;
        }
        return head.next;
    }
}

相關文章