LeetcodeOJ Add Two Numbers
来源:互联网 发布:国外开源软件 编辑:程序博客网 时间:2024/05/16 17:02
题目
链接
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
分析
两个单链表的各个节点的数字相加,而且包括进位,那用一个变量carry保存进位就可以了。本体主要还是链表的使用,比如如何return ListNode*的节点。
这儿,我们先定义要输出的链表:
ListNode* result = new ListNode(0);ListNode* temp = result;
输出链表这样就可以了:
return result->next;
还是比较简单的,temp 用于向下一个节点写值:
temp->next=new ListNode((a+b+carry)%10);temp=temp->next;
代码
/** * 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* result = new ListNode(0); ListNode* temp = result; int a,b,carry=0; while(l1!=NULL || l2!=NULL){ a=0; if(l1!=NULL){ a=l1->val; l1=l1->next; } b=0; if(l2!=NULL){ b=l2->val; l2=l2->next; } temp->next=new ListNode((a+b+carry)%10); carry=(a+b+carry)/10; temp=temp->next; } if(carry==1){ temp->next= new ListNode(1); } return result->next; }};
http://blog.csdn.net/yueming6121/article/details/45534067
0 0
- LeetcodeOJ Add Two Numbers
- LeetCodeOJ:2. Add Two Numbers
- LeetCodeOJ——2.Add Two Numbers
- Add two numbers & Add binary
- LeetCode: Add Two Numbers
- Add Two Numbers
- LeetCode: Add Two Numbers
- [LeetCode]Add Two Numbers
- LeetCode Add Two Numbers
- Leetcode: Add Two Numbers
- Add Two Numbers
- LeetCode : Add Two Numbers
- LeetCode Add Two Numbers
- [LeetCode] Add Two Numbers
- LeetCode4: Add Two Numbers
- Leetcode : Add Two Numbers
- Add Two Numbers
- 【leetcode】Add Two Numbers
- 封装好的测量View的宽和高
- KVC & KVO
- 调用支付宝接口开发遇到的错误
- 何新生的英语史(五)——稍有基础、疯狂积累阶段
- myeclipse web project转换为maven project
- LeetcodeOJ Add Two Numbers
- 多处理机调度问题(NP)
- Android之属性动画(二)
- eclipse 修改设置Ctrl+Shift+F长度
- python验证码识别
- iOS中使用block传值
- 【小明开发一百问】(一)如何制作手机软件演示视频
- Art of Multiprocessor Programming 答案 ch8 p93
- SDK 无法更新解决方案