aboutsummaryrefslogtreecommitdiff
path: root/other/add_two_num2.cpp
diff options
context:
space:
mode:
authorJack Sangdahl <[email protected]>2025-03-10 00:36:13 -0600
committerJack Sangdahl <[email protected]>2025-03-10 00:36:13 -0600
commit7c60dee83b436e8e8a667bf9f191beced8de4fc3 (patch)
treeeb7a24ee2067f92245c57bb118e85a1baf15df50 /other/add_two_num2.cpp
parent5d7cdc215e4ba1ec4cbb24c084cccb5e5e641468 (diff)
downloadleetcode-7c60dee83b436e8e8a667bf9f191beced8de4fc3.tar.gz
leetcode-7c60dee83b436e8e8a667bf9f191beced8de4fc3.zip
chore: move cpp and rust code to directory
Diffstat (limited to 'other/add_two_num2.cpp')
-rw-r--r--other/add_two_num2.cpp56
1 files changed, 56 insertions, 0 deletions
diff --git a/other/add_two_num2.cpp b/other/add_two_num2.cpp
new file mode 100644
index 0000000..8cc7121
--- /dev/null
+++ b/other/add_two_num2.cpp
@@ -0,0 +1,56 @@
+// 445. Add Two Numbers II
+#include "leetcode.h"
+
+/*
+ * given two non-empty linked lists representing two non-negative integers. the
+ * most significant digit comes first and each of their nodes contains a single
+ * digit. add the two numbers and return the same as a linked list. you may
+ * assume the two numbers do not contain any leading zero, except the number 0
+ * itself.
+ */
+
+class Solution {
+ ListNode *append(int val, ListNode *head) {
+ ListNode *tmp = new ListNode(val);
+ tmp->next = head;
+ return tmp;
+ }
+
+public:
+ ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) {
+ int n1 = 0, n2 = 0, carry = 0;
+ ListNode *curr1 = l1, *curr2 = l2, *ans = NULL;
+ while (curr1)
+ curr1 = curr1->next, n1++;
+ while (curr2)
+ curr2 = curr2->next, n2++;
+ curr1 = l1, curr2 = l2;
+ while (n1 && n2) {
+ int sum = 0;
+ if (n1 >= n2) {
+ sum += curr1->val;
+ curr1 = curr1->next;
+ n1--;
+ }
+ if (n2 > n1) {
+ sum += curr2->val;
+ curr2 = curr2->next;
+ n2--;
+ }
+ ans = append(sum, ans);
+ }
+ curr1 = ans;
+ ans = NULL;
+ while (curr1) {
+ curr1->val += carry;
+ carry = curr1->val / 10;
+ ans = append(curr1->val % 10, ans);
+ curr2 = curr1;
+ curr1 = curr1->next;
+ delete curr2;
+ }
+ if (carry)
+ ans = append(1, ans);
+ return ans;
+ }
+};