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); } };
时间: 2024-10-10 06:49:12