题目链接
题目名称:2. Add Two Numbers
题目描述:
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
C++代码:
#include <string>
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
string str1 = "", str2 = "";
while (l1 != NULL) {
str1 += (l1->val + '0');
l1 = l1->next;
}
while (l2 != NULL) {
str2 += (l2->val + '0');
l2 = l2->next;
}
int len1 = str1.length();
int len2 = str2.length();
int len = 0;
if (len1 < len2) {
for (int i = 0; i < len2 - len1; i++)
str1 += '0';
len = len2;
}
else {
for (int i = 0; i < len1 - len2; i++)
str2 += '0';
len = len1;
}
int add_1 = 0;
ListNode* pt = new ListNode(0);
ListNode* temp = pt;
for (int i = 0; i < len; i++)
{
int sum = int(str1[i] + str2[i] + add_1 - 96);
if (i == len - 1) {
if (sum >= 10) {
temp->next = new ListNode(1);
temp->val += sum - 10;
}
else
temp->val = sum;
return pt;
}
else if (sum >= 10) {
add_1 = 1;
temp->val = sum - 10;
}
else {
add_1 = 0;
temp->val = sum;
}
temp->next = new ListNode(0);
temp = temp->next;
}
return pt;
}
};
代码效率:
未来工作:
学习leetcode上他人算法,并将算法效率提高至击败50%人的水平。