Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class SolutionLinear {
- public:
- ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
- ListNode *list = new ListNode((l1->val + l2->val) % 10), *current = list;
- bool carry = (l1->val + l2->val) >= 10;
- for(ListNode *i1 = l1->next, *i2 = l2->next;
- i1 || i2;
- i1 = i1 ? i1->next : nullptr,
- i2 = i2 ? i2->next : nullptr) {
- int v1 = i1 ? i1->val : 0,
- v2 = i2 ? i2->val : 0;
- current->next = new ListNode((v1 + v2 + carry) % 10);
- carry = (v1 + v2 + carry) >= 10;
- current = current->next;
- }
- if(carry)
- current->next = new ListNode(1);
- return list;
- }
- };
- int test() {
- for(int i = 0; i < 9; i++);
- }
- class SolutionRecursive {
- public:
- ListNode* addTwoNumbers(ListNode* l1, ListNode* l2, bool carry = false) {
- if(!l1 && !l2)
- return carry ? new ListNode(1) : nullptr;
- int v1 = l1 ? l1->val : 0,
- v2 = l2 ? l2->val : 0;
- return new ListNode((v1 + v2 + static_cast<int>(carry)) % 10,
- addTwoNumbers(l1 ? l1->next : nullptr,
- l2 ? l2->next : nullptr,
- (((v1 + v2 + static_cast<int>(carry)) >= 10))
- )
- );
- }
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement