我正在尝试解决这个问题 leetcode 问题 C 语言,这是我想出的代码:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
#include<math.h>
struct ListNode *addTwoNumbers(struct ListNode *l1, struct ListNode *l2) {
struct ListNode *temp;
struct ListNode *sum = NULL;
int num1 = 0;
int num2 = 0;
temp = l1;
int n = 0;
int i = 0;
while (temp != NULL) {
num1 = num1 + (temp->val * pow(10, i));
i++;
temp = temp->next;
}
temp = l2;
i = 0;
while (temp != NULL) {
num2 = num2 + (temp->val * pow(10, i));
i++;
temp = temp->next;
}
int add = num1 + num2;
int tem = add;
i = 0;
for (i = 0; tem > 0; i++) {
tem = tem / 10;
}
if (add == 0) {
struct ListNode *new = malloc(sizeof(struct ListNode));
new->val = 0;
new->next = sum;
sum = new;
}
while (add > 0 && i > 0) {
struct ListNode *new = malloc(sizeof(struct ListNode));
new->val = add / pow(10, (i - 1));
new->next = sum;
i--;
add = add % (int)(pow(10, i));
sum = new;
}
return sum;
}
我不明白为什么测试用例 l1 = [9]; 的输出为空 l2 = [1,9,9,9,9,9,9,9,9,9]。它在许多测试用例中都是正确的,但问题似乎出在 add 是 10 的倍数(可能)的测试用例中。请帮忙。
使用
ListNode
的要点是支持任意大的值。当使用将值存储在 int num1
中时,它就达不到目的了。
算法
num1=num1+(temp->val*pow(10,i));
是错误的,因为你想按照这些思路做一些事情num1 = 10 * num1 + temp->val
。