LEETCODE #2
问题描述
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.
0、背景
来源Leetcode题库Algorithms part,难度定级Medium。
参考Grandyang博客:Add Two Numbers 两数相加,语言选用C++,Java和Python。
1、算法
给定两个纯数字串,按位求和,注意进位,实际上就是大整数相加的模型,用于练习单链表的简单实现,C++的链表比Java难理解一点。注意最高位进位即可。
2、实现
a.CPP
/**
* 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) {
ListNode *ans = new ListNode(-1);
ListNode *temp = ans;
int bitt = 0;
while (l1 || l2)
{
int n1,n2;
if(l1) n1 = l1->val; else n1 = 0;
if(l2) n2 = l2->val; else n2 = 0;
int sum = n1 + n2 + bitt;
bitt = sum / 10;
temp->next = new ListNode(sum%10);
temp = temp->next;
if (l1) l1 = l1->next;
if (l2) l2 = l2->next;
}
if (bitt) temp->next = new ListNode(1);
return ans->next;
}
};
b.Java
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode ans = new ListNode(-1);
ListNode temp = ans;
int bitt = 0;
while (l1 != null || l2 != null)
{
int n1,n2;
if (l1 != null) n1 = l1.val; else n1 = 0;
if (l2 != null) n2 = l2.val; else n2 = 0;
int sum = n1 + n2 + bitt;
bitt = sum / 10;
temp.next = new ListNode(sum%10);
temp = temp.next;
if (l1 != null) l1 = l1.next;
if (l2 != null) l2 = l2.next;
}
if (bitt == 1) temp.next = new ListNode(1);
return ans.next;
}
}
c.Python
留待以后补充。
3、相关
留待补充乘除的相关实现。