LeetCode--Add Two Numbers
来源:互联网 发布:中世纪2全面战争优化9 编辑:程序博客网 时间:2024/05/19 03:25
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) { ListNode *head=new ListNode(0); ListNode *ptr=head; int carry=0; while(true) { if(l1!=NULL) { carry+=l1->val; l1=l1->next; } if(l2!=NULL) { carry+=l2->val; l2=l2->next; } ptr->val=carry%10; carry/=10; if(l1!=NULL||l2!=NULL||carry!=0) { ptr->next=new ListNode(0); ptr=ptr->next; } else break; } return head; }};
阅读全文
1 0
- LeetCode: Add Two Numbers
- LeetCode: Add Two Numbers
- [LeetCode]Add Two Numbers
- LeetCode Add Two Numbers
- Leetcode: Add Two Numbers
- LeetCode : Add Two Numbers
- LeetCode Add Two Numbers
- [LeetCode] Add Two Numbers
- Leetcode : Add Two Numbers
- 【leetcode】Add Two Numbers
- [LeetCode]Add Two Numbers
- leetcode Add Two Numbers
- LeetCode-Add Two Numbers
- [leetcode] Add Two Numbers
- [LeetCode] Add Two Numbers
- LeetCode - Add Two Numbers
- LeetCode | Add Two Numbers
- 【leetcode】Add Two Numbers
- 数据库引擎浅识
- Android-环境搭建
- Vue $set 数组不能更新视图的问题
- 省市联动的实现
- EventBus分析--事件的注册
- LeetCode--Add Two Numbers
- centos7下nginx的基本配置
- Win/Lin 双系统时间错误的调整
- JAVA泛型详解
- [分块] Codeforces 436F && Zepto Code Rush 2014 F. Banners
- SSAS项目创建
- mysql_5.5.48主从配置
- static 学习笔记
- 1