力扣2. 两数相加

2021-12-08  本文已影响0人  阿丹_90

题目

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/add-two-numbers

答案

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode result = new ListNode();
        ListNode cr = result, cl1 = l1, cl2 = l2;
        int next = 0;
        while (cl1 != null || cl2 != null || next > 0) {
            int val1 = 0, val2 = 0;
            if (cl1 != null) {
                val1 = cl1.val;
                cl1 = cl1.next;
            }
            if (cl2 != null) {
                val2 = cl2.val;
                cl2 = cl2.next;
            }
            int val = val1 + val2 + next;
            cr.val = val % 10;
            next = val / 10;
            if (cl1 != null || cl2 != null || next > 0) {
                ListNode nr = new ListNode();
                cr.next = nr;
                cr = nr;
            }
        }
        return result;
    }
}
上一篇下一篇

猜你喜欢

热点阅读