LeetCode 2. Add Two Numbers
来源:互联网 发布:淘宝加盟骗局 编辑:程序博客网 时间:2024/06/11 15:24
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
题目大意是通过链表把数字加起来,其中还有进位。
第一次提交直接WA了,因为有个数据是[5]+[5],输出应该是[0,1],也就是5+5=10,一开始没考虑到。。。
下面是我用c++语言写的代码,比较拙劣。
/** * 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 carry = 0; ListNode* ans = (ListNode*)malloc(sizeof(ListNode)); *ans = ListNode(-1); ListNode* res = ans; ListNode* temp = (ListNode*)malloc(sizeof(ListNode)); *temp = ListNode(0); while(l1!=NULL&&l2!=NULL){ temp->val = carry; carry = 0; temp->val += l1->val; temp->val += l2->val; l1 = l1->next; l2 = l2->next; carry = temp->val/10; temp->val = temp->val%10; if(ans->val!=-1){ ans->next = (ListNode*)malloc(sizeof(ListNode)); ans = ans->next; *ans = ListNode(temp->val); } else{ *ans = ListNode(temp->val); } } if(l1==NULL){ while (l2!=NULL) { temp->val = carry; carry = 0; temp->val += l2->val; l2 = l2->next; carry = temp->val/10; temp->val = temp->val%10; if(ans->val!=-1){ ans->next = (ListNode*)malloc(sizeof(ListNode)); ans = ans->next; *ans = ListNode(temp->val); } else{ *ans = ListNode(temp->val); } } }else{ while (l1!=NULL) { temp->val = carry; carry = 0; temp->val += l1->val; l1 = l1->next; carry = temp->val/10; temp->val = temp->val%10; if(ans->val!=-1){ ans->next = (ListNode*)malloc(sizeof(ListNode)); ans = ans->next; *ans = ListNode(temp->val); } else{ *ans = ListNode(temp->val); } } } if(l1==NULL&&l2==NULL&&carry!=0){ ans->next = (ListNode*)malloc(sizeof(ListNode)); ans = ans->next; *ans = ListNode(carry); } return res; }};
阅读全文
0 0
- [LeetCode]2.Add Two Numbers
- LeetCode 2.Add Two Numbers
- LeetCode --- 2. Add Two Numbers
- [Leetcode] 2. Add Two Numbers
- 【leetcode】2. Add Two Numbers
- leetcode 2. Add Two Numbers
- LeetCode-2.Add Two Numbers
- [leetcode] 2. Add Two Numbers
- 【LeetCode】2. Add Two Numbers
- LeetCode - 2. Add Two Numbers
- LeetCode 2.Add Two Numbers
- LeetCode 2. Add Two Numbers
- Leetcode 2. Add Two Numbers
- 2. Add Two Numbers LeetCode
- leetcode 2. Add Two Numbers
- LeetCode-2. Add Two Numbers
- LeetCode 2. Add Two Numbers
- 2. Add Two Numbers----LeetCode
- windows下Java环境变量的配置
- 输入格式不对
- JS 逻辑判断选择器 || &&
- Literal控件的用法
- 洛谷P1160 队列安排(模拟)
- LeetCode 2. Add Two Numbers
- 算法之康托展开式
- [17-05-14]普及模拟【题解】
- python learning4
- 如何遍历某种类型的控件
- 本地发布地图服务到远程Arcgis Server服务器流程及可能存在的几个问题
- 赫夫曼树(最优二叉树)-数据结构(16)
- JDK下载安装以及环境变量配置图文详解
- JAVA的23种设计模式---原型模式