讨论/综合讨论/求教!在xcode上面输入数据运行后没有问题,但是提交就是解答错误。困扰了一晚上。/
求教!在xcode上面输入数据运行后没有问题,但是提交就是解答错误。困扰了一晚上。

题目:两数相加(代码是用C语言写的)
image.png

代码如下
struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2)
{
struct ListNode* p1 = l1;
struct ListNode* p2 = l2;
int val1 = 0, val2 = 0, count = 0, power = 0;

while(p1 != NULL)
{
    val1 = val1 + pow(10,power) * p1->val;
    power ++;
    p1 = p1->next;
}
power = 0;
 while(p2 != NULL)
{
    val2 = val2 + pow(10,power) * p2->val;
    power ++;
    p2 = p2->next;
}
int total = val1 + val2;
int val3 = total;

struct ListNode* p = NULL;
struct ListNode* current = NULL;
struct ListNode* head = (struct ListNode*)malloc(sizeof(struct ListNode));
head->next = NULL;
if(val3 == 0)
{
    p = (struct ListNode*)malloc(sizeof(struct ListNode));
    p->val = 0;
    p->next = NULL;
    head->next = p;
}
else
{
while(total != 0)
{
    total /= 10;
    count ++;
}

int *v_arr = (int *)malloc(count*sizeof(int));
int i = 0, temp = count;
while(val3 != 0)
{
    v_arr[i] = val3 / pow(10,temp-1);
    val3 = val3 % (int)pow(10,temp-1);
    i++;
    temp--;
}

while(count != 0)
{
    p = (struct ListNode*)malloc(sizeof(struct ListNode));
    p->val = v_arr[count-1];
    p->next = NULL;
    if(head->next == NULL){
        head->next = p;
        current = p;
    }
    else{
        current -> next = p;
        current = p;
    }
    count --;
}
}

return head->next;

}

展开讨论
共 2 个讨论

一般出现奇怪的数字就是没有初始化哈哈哈

看你的输出很明显就是溢出了嘛