002. 两数相加
大约 1 分钟
002. 两数相加中等
解法:
/**
* 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(0); // 返回结果链表
ListNode cur = result; // 链表头
int i = 0; // 进位
while(l1 != null || l2 != null || i != 0){
int x = l1 != null ? l1.val : 0; // 溢出,赋值为0
int y = l2 != null ? l2.val : 0;
cur.next = new ListNode((x+y+i)%10);
i = (x+y+i)/10; // 进位
cur = cur.next;
if(l1 != null)l1 = l1.next;
if(l2 != null)l2 = l2.next;
}
return result.next;
}
}
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution(object):
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
res = ListNode()
cur = res
carry = 0
while l1 is not None or l2 is not None or carry != 0:
x = l1.val if l1 else 0
y = l2.val if l2 else 0
total = x + y + carry
carry = total // 10
cur.next = ListNode(total % 10)
cur = cur.next
if l1: l1 = l1.next
if l2: l2 = l2.next
return res.next
Powered by Waline v2.15.5