提问人:Breach 提问时间:11/9/2023 最后编辑:Captain GiraffeBreach 更新时间:11/9/2023 访问量:13
将存储在两个链表中的值相加,并返回两个数字之和的链表
add the value stored in two linked lists and return a linked lists with the sum of the two numbers
问:
我的代码似乎可以工作,因为它几乎通过了这个 leetcode 问题的所有测试,但是其中一个测试包含一个非常大的值,这会破坏我的代码。
特别是破坏我的代码的测试用例是
l1 = [1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1]
l2 = [5,6,4]
我明白问题是什么,值很大,可以存储在很长的 int 中,但我不知道如何解决这个问题。
这是我的代码
#include <cmath>
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
vector<int> extractDigits(long long int num){
vector<int> digits;
if(num == 0){ //in case vector only contains 0 as its val
digits.push_back(num);
}
while (num != 0) {
long long int digit = num % 10;
digits.push_back(digit);
num /= 10;
}
return digits;
}
void populateVector(vector<int> &vec, ListNode* list){
while(list != NULL){
vec.push_back(list->val);
list = list->next;
}
}
unsigned long long int vecToInt(vector<int> vec){
int size = vec.size();
int exp = size - 1;
long long int num = 0;
//cout<<size<<endl;
for(int x = 0; x < size; x++){ //turns vector into number to be added
unsigned long long int temp = 0;
if(vec.at(x) != 0){
temp = vec.at(x);
temp = temp * pow(10,exp);
}
exp--;
num += temp;
}
cout<<num<<endl;
return num;
}
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
ListNode* temp, asnwer;
vector<int> digits1, digits2, sum;
unsigned long long int number1 = 0 , number2 = 0;
populateVector(digits1, l1);
populateVector(digits2, l2);
reverse(digits1.begin(), digits1.end());
reverse(digits2.begin(), digits2.end());
number1 = vecToInt(digits1);
number2 = vecToInt(digits2);
number1 += number2;
//cout<<number1<<endl;
sum = extractDigits(number1);
ListNode* final_list = NULL;
for(int digit : sum){
if(!final_list){
final_list = new ListNode(digit);
temp = final_list;
}
else{
temp->next = new ListNode(digit);
temp = temp->next;
}
}
return final_list;
}
};
答: 暂无答案
评论