leetcode-solution C++【2】---add two numbers
2018-01-29 21:02
615 查看
原题
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
比较简单,就是两个链表相加,这里要注意进位的问题,以及最高位相加是否大于10
先写在这里,具体细节 后面再添加
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 Explanation: 342 + 465 = 807.
比较简单,就是两个链表相加,这里要注意进位的问题,以及最高位相加是否大于10
/** * 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 list(0); ListNode *p=&list; //ListNode* p = new ListNode(0); //ListNode* newhead = p; int cn=0; while(l1||l2) { int val=cn+(l1 ? l1->val : 0)+(l2 ? l2->val : 0); cn=val/10; val=val%10; p->next=new ListNode(val); p=p->next; if(l1) l1=l1->next; if(l2) l2=l2->next; } if(cn!=0) { p->next=new ListNode(cn); p=p->next; } return list.next; } };
先写在这里,具体细节 后面再添加
相关文章推荐
- LeetCode #2 Add Two Numbers Cpp Solution
- 【C++】【LeetCode】【指针】2. Add Two Numbers
- Leetcode 2. Add Two Numbers The Solution of Python and Javascript
- [c++] LeetCode Add Two Numbers问题
- LeetCode : 2 Add Two Numbers C++
- [LeetCode 2] Add Two Numbers Solution
- LeetCode Add Two Numbers C++
- LeetCode 2. Add Two Numbers(C++)
- leetcode-02-add two numbers-c++
- solution about leetcode problem 2 add Two Numbers
- leetcode: add two numbers , hash search solution, java. O(n)
- LeetCode 2. Add Two Numbers (C++/python/js实现)
- 【leetcode 2】 Add Two Numbers(C++)
- [C++]LeetCode: 108 Add Two Numbers (反序链表求和)
- [LeetCode] Add Two Numbers(C++)
- [LeetCode] Add Two Numbers, Solution
- LeetCode刷题(C++)——Add Two Numbers(Medium)
- [LeetCode] Add Two Numbers, Solution
- LeetCode 2. Add Two Numbers(C++版)
- leetcode 445 Add Two Numbers II C++