gpt4 book ai didi

c++ - 我的输出中有一个额外的 0,这是为什么

转载 作者:行者123 更新时间:2023-11-28 04:31:41 24 4
gpt4 key购买 nike

所以我正在练习 leetcode,这就是问题:

给定两个非空链表,代表两个非负数整数。数字以相反的顺序存储,并且它们的每个节点包含一个数字。将这两个数字相加并将其作为链表返回。

您可以假设这两个数字不包含任何前导零,除了数字 0 本身。

例子:

输入:(2 -> 4 -> 3) + (5 -> 6 -> 4)

输出:7 -> 0 -> 8

解释:342 + 465 = 807。

/**
* 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) {
vector<int> V1;
vector<int> V2;
int sum1 = 0;
int sum2 = 0;
ListNode *result = new ListNode(0);
auto l0 = result;
while(l1) {
V1.push_back(l1->val);
l1=l1->next;
}

for (auto it1 = V1.rbegin(); it1 != V1.rend(); it1++) {
sum1 = sum1 * 10 + (*it1);
}

while(l2) {
V2.push_back(l2->val);
l2=l2->next;
}

for (auto it2 = V2.rbegin(); it2 != V2.rend(); it2++) {
sum2 = sum2 * 10 + (*it2);
}
int sum3 = sum1 + sum2;
while (sum3 !=0) {
int extract = sum3 % 10;
l0->next = new ListNode(extract);
sum3 /= 10;
l0=l0->next;
}

return result;


}
};

当我运行它时,我的输出中总是有额外的 0,例如:

您的意见[7,2,7] [2,4,2]

你的答案[0,9,6,9]

预期答案[9,6,9]

我知道有更聪明的方法来解决这个问题,但我想先尝试用我的方式解决它

最佳答案

这是因为您正在创建第一个带有 0 的节点。您有两个解决方案:

  • 跳过函数末尾的第一个元素(解决方法):

    ListNode* aux = result;
    result = result->next;
    delete aux;
    return result;
  • 不将列表节点初始化为零,而是使用空指针:

s

ListNode *result = nullptr;

// More code...

while (sum3 !=0) {
int extract = sum3 % 10;
if (l0 == nullptr) {
result = new ListNode(extract);
l0 = result;
}
else
l0->next = new ListNode(extract);
sum3 /= 10;
l0=l0->next;
}

当然,还有更好的解决方案。您可以直接求和,而无需使用额外的 vector/内存。

关于c++ - 我的输出中有一个额外的 0,这是为什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52723284/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com