标签:一个 numbers 相加 init sum 官方 nod 处理 solution
这题medium,但思路挺简单的。模拟下就可以
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
ListNode *rst = new ListNode(0);
ListNode *head = rst;
int tmp = 0;
while(l1 && l2) {
int sum = l1->val + l2->val + tmp;
rst->next = new ListNode(sum%10);
tmp = sum/10;
rst = rst->next;
l1 = l1->next;l2 = l2->next;
}
while(l1) {
int sum = l1->val + tmp;
rst->next = new ListNode(sum%10);
tmp = sum/10;
rst = rst->next;
l1 = l1->next;
}
while(l2) {
int sum = l2->val + tmp;
rst->next = new ListNode(sum%10);
tmp = sum/10;
rst = rst->next;
l2 = l2->next;
}
if(tmp>0) {
rst->next = new ListNode(1);
}
return head->next;
}
};
对比下官方解答,把l1,l2短的那个“补齐”了处理,可以在一个while里面写完。思路是一样的
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode dummyHead = new ListNode(0);
ListNode p = l1, q = l2, curr = dummyHead;
int carry = 0;
while (p != null || q != null) {
int x = (p != null) ? p.val : 0;
int y = (q != null) ? q.val : 0;
int sum = carry + x + y;
carry = sum / 10;
curr.next = new ListNode(sum % 10);
curr = curr.next;
if (p != null) p = p.next;
if (q != null) q = q.next;
}
if (carry > 0) {
curr.next = new ListNode(carry);
}
return dummyHead.next;
}
标签:一个 numbers 相加 init sum 官方 nod 处理 solution
原文地址:https://www.cnblogs.com/pusidun/p/13636332.html