LeetCode *** 2. Add Two Numbers
2016-04-05 11:47
267 查看
题目:
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
分析:
一位一位的加,注意要保留进位,同时l1与l2可能位数不一样,也需要注意,大概就这样吧。我RE了很久,我也不知道为啥。。。我到现在都没明白。。我cpp还是忘得差不多了。。心塞。。。
代码:
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
分析:
一位一位的加,注意要保留进位,同时l1与l2可能位数不一样,也需要注意,大概就这样吧。我RE了很久,我也不知道为啥。。。我到现在都没明白。。我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 *res,*restmp,*l1tmp,*l2tmp; l1tmp=l1;l2tmp=l2; int CA=0; res=new ListNode(0); restmp=res; while(l1tmp!=NULL&&l2tmp!=NULL){ int tmp=l1tmp->val+l2tmp->val+CA; CA=tmp/10; restmp->next=new ListNode(tmp%10); restmp=restmp->next; // if(l1->next!=NULL) l1tmp=l1tmp->next; // if(l2->next!=NULL) l2tmp=l2tmp->next; } while(l1tmp!=NULL&&l2tmp==NULL){ int tmp=l1tmp->val+CA; CA=tmp/10; restmp->next=new ListNode(tmp%10); restmp=restmp->next; l1tmp=l1tmp->next; } while(l1tmp==NULL&&l2tmp!=NULL){ int tmp=l2tmp->val+CA; CA=tmp/10; restmp->next=new ListNode(tmp%10); restmp=restmp->next; l2tmp=l2tmp->next; } if(CA!=0){ restmp->next=new ListNode(CA); restmp=restmp->next; } return res->next; } };
相关文章推荐
- Linux下安装MySQL RPM-Bundle.tar
- gdb在运行maintenance info program-spaces命令时coredump
- fir.im Weekly - 如何做一个出色的程序员
- chrome扩展第三方浏览器下载安装
- eclipse导入class文件
- 【LeetCode】Increasing Triplet Subsequence(334)
- CSS艺术之---负margin之美
- 基于git的源代码管理模型——git flow
- 异常:org.apache.ibatis.reflection.ReflectionException
- 对接近有序的数组排序
- 开发环境配置-maven的安装、配置与使用-6
- mysql 之 checkpoint和LSN详解
- 自定义控件2
- 参数列表中的self:显式不等于冗余
- Ubuntu14.4下Sublime Text 3无法输入中文解决方法
- 直方图
- static的含义
- Android Studio 使用笔记
- Tengine 的安装与使用
- 如何遍历newtonsoft.json的JObject里的JSON数据