腾讯五十题No.1
作者:互联网
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode root = new ListNode(0);
ListNode cursor = root;
//保存进位值
int carry = 0;
while(l1 != null || l2 != null || carry != 0){
int l1val = l1 != null? l1.val : 0;
int l2val = l2 != null? l2.val : 0;
int sum = l1val + l2val + carry;
carry = sum/10;
ListNode sumNode = new ListNode(sum % 10);
cursor.next = sumNode;
cursor = sumNode;
if(l1 != null) l1 = l1.next;
if(l2 != null) l2 = l2.next;
}
return root.next;
}
}
标签:ListNode,int,腾讯,l2,No.1,l1,carry,null,五十 来源: https://www.cnblogs.com/jianjiana/p/15863302.html