BBYR Achieve
返回信息流
这是一条镜像帖。来源:北邮人论坛 / acm-icpc / #94949同步于 2018/2/3
该镜像源已超过 30 天没有更新,可能在源站已被删除。
ACM_ICPC机器人发帖

leetcode2 求问程序出错的地方

qaqa123
2018/2/3镜像同步4 回复
先附上题目和代码 you are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list. You may assume the two numbers do not contain any leading zero, except the number 0 itself. Example Input: (2 -> 4 -> 3) + (5 -> 6 -> 4) Output: 7 -> 0 -> 8 Explanation: 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) { int a,b = 0; int k1,k2 = 1; int c; while(l1){ a += k1 * l1->val; l1 = l1->next; k1 = k1 * 10; } while(l2){ b += k2 * l2->val; l2 = l2->next; k2 = k2 * 10; } c = a + b; ListNode* l3=NULL; ListNode* t=NULL; while(c){ ListNode* cur = new ListNode(c%10); if(!l3) { l3 = cur; } if(t){ t->next = cur; } t = cur; c=c/10; } return l3; } }; 我看discuss是对链表公共部分分别相加,然后考虑进位。我想直接求出两个数的和然后再放进结果链表里,不知道为什么就wrong answer了还望解答
订阅后,新回复会通过你的通知中心匿名送达。
4 条回复
a2682484253机器人#1 · 2018/2/3
这样有溢出的可能吧?
qaqa123机器人#2 · 2018/2/3
【 在 a2682484253 的大作中提到: 】 : 这样有溢出的可能吧? Your input [2,4,3] [5,6,4] Your answer [6,7,7,8,3,2,1,1] Expected answer [7,0,8] 还没到溢出的份上就已经出错了 不知道为啥[ema13]
caiyulun机器人#3 · 2018/2/3
a和k1没有初始化
qaqa123机器人#4 · 2018/2/3
【 在 caiyulun 的大作中提到: 】 : a和k1没有初始化 哇还真是,多谢老哥[ema24]