2. Add Two Numbers
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.
题解:(方法不好,待优化)
将两个数以逆序(从左到右对应低位到高位)存入两个链表,然后将两个数求和的结果逆序存入新的链表中输出。
来个炒鸡无脑的解题思路,首先创建一个头结点,让指针l指向该头结点地址;int bit = 0用来表示是否进位,有进位则将bit值赋为1;将链表各节点值加上进位求和,再对10取余得到新的节点值;用新的节点值替换其中一个链表l1的节点值,进而通过l->next = l1将该位求和后的值连接在新链表中,直到原来的两个链表中有一个为空;将剩余的链表对应的各节点值和对应的进位值求和后对10取余获得新的节点值,连接到新链表的结尾。
My Solution(C/C++完整实现):
#include <cstdio>
#include <iostream>
using namespace std;
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution {
public:
ListNode * addTwoListNumber(ListNode *l1, ListNode *l2) {
ListNode result(0);
ListNode *l = &result;
int bit = 0;
int sum;
while(l1 && l2) {
sum = l1->val + l2->val + bit;
l1->val = sum % 10;
bit = sum / 10;
l->next = l1;
l1 = l1->next;
l2 = l2->next;
l = l->next;
}
while (l1) {
sum = l1->val + bit;
l1->val = sum % 10;
bit = sum / 10;
l->next = l1;
l1 = l1->next;
l = l->next;
}
while (l2) {
sum = l2->val + bit;
l2->val = sum % 10;
bit = sum / 10;
l->next = l2;
l2 = l2->next;
l = l->next;
}
if (bit == 1) {
l->next = new ListNode(1); //为值为1的节点分配内存空间
}
return result.next;
}
};
int main() {
ListNode a1(2);
ListNode b1(4);
ListNode c1(3);
ListNode a2(5);
ListNode b2(6);
ListNode c2(4);
a1.next = &b1;
b1.next = &c1;
a2.next = &b2;
b2.next = &c2;
Solution s;
ListNode *result = s.addTwoListNumber(&a1, &a2);
while (result) {
printf("%d->", result->val);
result = result->next;
}
return 0;
}
结果:
7->0->8->
My Solution(Python):
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
l = ListNode(0)
result = l
bit = 0
while l1 and l2:
l1.val, bit = (l1.val + l2.val + bit) % 10, (l1.val + l2.val + bit) // 10
l.next = l1
l1, l2, l = l1.next, l2.next, l.next
while l1:
l1.val, bit = (l1.val + bit) % 10, (l1.val + bit) // 10
l.next = l1
l1, l = l1.next, l.next
while l2:
l2.val, bit = (l2.val + bit) % 10, (l2.val + bit) // 10
l.next = l2
l2, l = l2.next, l.next
if bit == 1:
l.next = ListNode(1)
return result.next
Reference:
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
carry = 0
root = n = ListNode(0)
while l1 or l2 or carry:
v1 = v2 = 0
if l1:
v1 = l1.val
l1 = l1.next
if l2:
v2 = l2.val
l2 = l2.next
carry, val = divmod(v1+v2+carry, 10)
n.next = ListNode(val)
n = n.next
return root.next