Leetcode刷题总结: 445. Add Two Numbers II
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Leetcode刷题总结: 445. Add Two Numbers II相关的知识,希望对你有一定的参考价值。
You are given two non-empty linked lists representing two non-negative integers. The most significant digit comes first 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.
Follow up:
What if you cannot modify the input lists? In other words, reversing the lists is not allowed.
Example:
Input: (7 -> 2 -> 4 -> 3) + (5 -> 6 -> 4) Output: 7 -> 8 -> 0 -> 7
思路一:
题目说了代表两个int型的数,第一个思路是我直接将这个list转成int型的正整数, 然后两个int型相加,为了防止溢出,用long存储sum;
再将sum转换成list;
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: unsigned int getNum(ListNode *pnode) { unsigned int result = 0; while(pnode != NULL) { result = result*10 + pnode->val; pnode = pnode->next; } return result; } ListNode* transNumToList(long num) { ListNode *cur = new ListNode(num%10); num = num/10; while (num > 0) { int res = num%10; num /= 10; ListNode *pnew = new ListNode(res); pnew->next = cur; cur = pnew; } return cur; } ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) { unsigned int num1 = getNum(l1); unsigned int num2 = getNum(l2); cout << num1 << endl; cout << num2 << endl; unsigned long sum = num1+num2; return transNumToList(sum); } };
以上是关于Leetcode刷题总结: 445. Add Two Numbers II的主要内容,如果未能解决你的问题,请参考以下文章
Leetcode445. Add Two Numbers II
leetcode 445. Add Two Numbers II
LeetCode 445. 两数相加 II(Add Two Numbers II)
[Leetcode] 445. Add Two Numbers II