Advertisement
dreadmachine

cmp.cpp

Oct 18th, 2021
702
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.28 KB | None | 0 0
  1. class SolutionLinear {
  2. public:
  3.     ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
  4.         ListNode *list = new ListNode((l1->val + l2->val) % 10), *current = list;
  5.         bool carry = (l1->val + l2->val) >= 10;
  6.         for(ListNode *i1 = l1->next, *i2 = l2->next;
  7.             i1 || i2;
  8.             i1 = i1 ? i1->next : nullptr,
  9.             i2 = i2 ? i2->next : nullptr) {
  10.                 int v1 = i1 ? i1->val : 0,
  11.                     v2 = i2 ? i2->val : 0;
  12.                 current->next = new ListNode((v1 + v2 + carry) % 10);
  13.                 carry = (v1 + v2 + carry) >= 10;
  14.                 current = current->next;
  15.             }
  16.             if(carry)
  17.                 current->next = new ListNode(1);
  18.         return list;
  19.     }
  20. };
  21.  
  22. int test() {
  23.     for(int i = 0; i < 9; i++);
  24. }
  25.  
  26. class SolutionRecursive {
  27. public:
  28.     ListNode* addTwoNumbers(ListNode* l1, ListNode* l2, bool carry = false) {
  29.         if(!l1 && !l2)
  30.             return carry ? new ListNode(1) : nullptr;
  31.         int v1 = l1 ? l1->val : 0,
  32.             v2 = l2 ? l2->val : 0;
  33.         return new ListNode((v1 + v2 + static_cast<int>(carry)) % 10,
  34.             addTwoNumbers(l1 ? l1->next : nullptr,
  35.                 l2 ? l2->next : nullptr,
  36.                 (((v1 + v2 + static_cast<int>(carry)) >= 10))
  37.             )
  38.         );
  39.     }
  40. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement