Advertisement
dimon-torchila

Untitled

Nov 20th, 2022
808
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.94 KB | None | 0 0
  1. /**
  2.  * Definition for singly-linked list.
  3.  * struct ListNode {
  4.  *     int val;
  5.  *     ListNode *next;
  6.  *     ListNode() : val(0), next(nullptr) {}
  7.  *     ListNode(int x) : val(x), next(nullptr) {}
  8.  *     ListNode(int x, ListNode *next) : val(x), next(next) {}
  9.  * };
  10.  */
  11. class Solution {
  12. public:
  13.     ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
  14.         int step = 0;
  15.         auto head = new ListNode();
  16.         while(l1 != NULL || l2 != NULL || step){
  17.             int sum = 0;
  18.             head = new ListNode();
  19.             if(l1 != NULL){
  20.                 sum += l1->val;
  21.                 l1 = l1->next;
  22.  
  23.             }
  24.             if(l2 != NULL){
  25.                 sum += l2->val;
  26.                 l2 = l2->next;
  27.             }
  28.             sum += step;
  29.             step = sum / 10;
  30.             head->val = sum % 10;
  31.             head->next = new ListNode();
  32.             head = head->next;
  33.         }
  34.         return head;
  35.     }
  36. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement