Evgenii Legotckoi
Маусым 13, 2022, 2:13 Т.Қ.

Leed Code Solutions - 002 - Екі санды қосу

Решение "Add Two Numbers" на Leet Code


  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. bool isOverheaded = false;
  15. int sum = 0;
  16. ListNode* head = new ListNode();
  17. ListNode* current = head;
  18.  
  19. ListNode* currentL1 = l1;
  20. ListNode* currentL2 = l2;
  21.  
  22. while (currentL1 != nullptr || currentL2 != nullptr)
  23. {
  24. if (!(currentL1 == l1 && currentL2 == l2))
  25. {
  26. current->next = new ListNode();
  27. current = current->next;
  28. }
  29. sum = 0;
  30.  
  31. if (currentL1)
  32. {
  33. sum += currentL1->val;
  34. currentL1 = currentL1->next;
  35. }
  36. if (currentL2)
  37. {
  38. sum += currentL2->val;
  39. currentL2 = currentL2->next;
  40. }
  41. if (isOverheaded)
  42. {
  43. ++sum;
  44. }
  45.  
  46. isOverheaded = sum > 9;
  47.  
  48. if (isOverheaded)
  49. {
  50. current->val = sum % 10;
  51. }
  52. else
  53. {
  54. current->val = sum;
  55. }
  56. }
  57.  
  58. if (isOverheaded)
  59. {
  60. current->next = new ListNode(1);
  61. }
  62.  
  63. return head;
  64. }
  65. };
GitHub репозиторийі

Мақала бойынша сұралады0сұрақтар(лар)

1

Ол саған ұнайды ма? Әлеуметтік желілерде бөлісіңіз!

Пікірлер

Тек рұқсаты бар пайдаланушылар ғана пікір қалдыра алады.
Кіріңіз немесе Тіркеліңіз