标签:https div nullptr ref ret ber gif linked leetcode
链接:https://leetcode-cn.com/problems/add-two-numbers/
代码:
/** * 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) { if(l1 == nullptr && l2 == nullptr) return nullptr; ListNode* head = new ListNode(-1); ListNode* cur = head; int carry = 0; while(l1 || l2) { int sum = 0; if(l1) { sum += l1->val; l1 = l1->next; } if(l2) { sum += l2->val; l2 = l2->next; } if(carry) { sum += 1; } cur->next = new ListNode(sum%10); carry = sum / 10; cur = cur->next; } if(carry) { cur->next = new ListNode(1); } return head->next; } };
思路:模拟字符串即可,进位,增加一位 blabla...
标签:https div nullptr ref ret ber gif linked leetcode
原文地址:https://www.cnblogs.com/FriskyPuppy/p/12953512.html