【重点】2.两数相加

题目

Python

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:
        tail = ListNode(-1)
        cur = tail
        cur1, cur2 = l1, l2
        carry = 0
        while cur1 != None or cur2 != None or carry:
            cur1_val = cur1.val if cur1 else 0
            cur2_val = cur2.val if cur2 else 0
            sum_val = cur1_val + cur2_val + carry
            cur_val = sum_val % 10
            carry = sum_val // 10
            cur.next = ListNode(cur_val)
            cur = cur.next
            cur1 = cur1.next if cur1 else None
            cur2 = cur2.next if cur2 else None

        return tail.next

Java

class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        if (l1 == null) {
            return l2;
        }
        if (l2 == null) {
            return l1;
        }
        ListNode head = null, cur = null;
        int carry = 0; // 进位
        while (l1 != null || l2 != null) {
            if (head == null) {
                int tmp = l1.val + l2.val;
                head = new ListNode(tmp % 10);
                cur = head;
                carry = tmp / 10;
                l1 = l1.next;
                l2 = l2.next;
            } else {
                int tmp = carry;
                if (l1 != null) {
                    tmp += l1.val;
                    l1 = l1.next;
                } 
                if (l2 != null) {
                    tmp += l2.val;
                    l2 = l2.next;
                }
                cur.next = new ListNode(tmp % 10);
                carry = tmp / 10;
                cur = cur.next;
            }
        }
        if (carry > 0) {
            cur.next = new ListNode(carry);
        }

        return head;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值