Advertisement
CyberN00b

Untitled

Nov 20th, 2022
133
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.02 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. auto start = head;
  17. while(true){
  18. int sum = 0;
  19. if (l1 != nullptr) {
  20. sum += l1->val;
  21. l1 = l1->next;
  22. }
  23. if (l2 != nullptr){
  24. sum += l2->val;
  25. l2 = l2->next;
  26. }
  27. sum += step;
  28. step = sum / 10;
  29. head->val = sum % 10;
  30. if (l1 != nullptr || l2 != nullptr || step) {
  31. head->next = new ListNode();
  32. head = head->next;
  33. } else
  34. break;
  35. }
  36. return start;
  37. }
  38. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement