您的位置:首页 > 其它

LeetCode 刷题笔录 Add Two Numbers

2013-10-02 15:04 363 查看
You are given two linked lists representing two non-negative numbers. 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.

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)

Output: 7 -> 0 -> 8

这题看起来没啥好说的,挨个顺序扫描就行了。要注意null的位置以及进位的问题。我的代码通不过测试。。。输入{9},{9}显示我的程序返回是{9},{1},而答案应该是{8},{1}。但是我把这代码在自己机器上用eclipse编译完了答案是正确的。。。也看不出自己哪里有错,可能是leetcode编译的问题吧。先记下来再说。

private boolean carry = false;      //set the flag to true if a carry is needed
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
// Start typing your Java solution below
// DO NOT write main() function
int first = add(l1.val, l2.val);
ListNode previous = new ListNode(first);      //the first node of the answer linked list
ListNode header = previous;
for(l1 = l1.next, l2 = l2.next; l1 != null && l2 != null; l1 = l1.next, l2 = l2.next){
previous = previous.next = new ListNode(add(l1.val, l2.val));
}
if(l1 == null && l2 == null){
if(carry){
previous = previous.next = new ListNode(1);
}
}
else if(l1 == null){
while(l2 != null){
previous = previous.next = new ListNode(l2.val);
l2 = l2.next;
}
}
else if(l2 == null){
while(l1 != null){
previous = previous.next = new ListNode(l1.val);
l1 = l1.next;
}
}

return header;
}
/**
* add the two numbers
* return the last digit of the result of the sum of the two numbers
* if the sum is larger than 10, set the carry flag to true
*/
private int add(int a, int b){
int result = a + b;
if(carry){
result++;
}
if(result < 10){
carry = false;
return result;
}
else{
result = result % 10;
carry = true;
return result;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: