2.|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.
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
思路 第一种:恢复输入的两个数,然后相加,再转换回去。这种方法会遇到数值范围的问题,不予考虑。
第二种:由于数字是以个位开头的,可以直接相加进位到下一位,最后如果多出进位的话再加一位即可。
实现
/**
* 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 ones = 0;
int tens = 0;
int rlt = 0;
ListNode* ans;
ListNode* last = NULL;
while(l1!=NULL || l2!=NULL){
if(l1 == NULL){
rlt = l2->val + tens;
l2 = l2->next;
}
else if(l2 == NULL){
rlt = l1->val + tens;
l1 = l1->next;
}
else{
rlt = l1->val + l2->val + tens;
l1 = l1->next;
l2 = l2->next;
}
ones = rlt % 10;
tens = rlt / 10;
ListNode* node = new ListNode(ones);
if(last == NULL){
ans = node;
last = node;
}
else{
last->next = node;
last = node;
}
}
if(tens>0){
ListNode* node = new ListNode(tens);
last->next = node;
}
return ans;
}
};
【2.|2. Add Two Numbers】主要考察对于链表的理解,不多说了。
推荐阅读
- 【Leetcode/Python】001-Two|【Leetcode/Python】001-Two Sum
- paddle|动手从头实现LSTM
- 推荐系统论文进阶|CTR预估 论文精读(十一)--Deep Interest Evolution Network(DIEN)
- Swift|Swift ----viewController 中addChildViewController
- NAT(网络地址转换技术)
- KubeDL HostNetwork(加速分布式训练通信效率)
- 清晨朗读327(How|清晨朗读327:How Successful People Network with Each Other)
- 神经网络Neural|神经网络Neural Networks
- 8-31|8-31 老Eastwood《骡子》
- AFNetworking上传图片