mirror of
https://github.com/Manoj-HV30/dsa-competitive-programming.git
synced 2026-05-16 19:35:22 +00:00
Leetcode day1
This commit is contained in:
@@ -0,0 +1,27 @@
|
||||
class Solution{
|
||||
public:
|
||||
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2){
|
||||
ListNode* dummyhead = new ListNode(0);
|
||||
ListNode* tail = dummyhead;
|
||||
bool carry = 0;
|
||||
|
||||
while(l1 || l2|| carry){
|
||||
int digit1 = (l1!=nullptr) ? l1->val : 0;
|
||||
int digit2 = (l2!=nullptr) ? l2->val : 0;
|
||||
|
||||
int sum = digit1+digit2+carry;
|
||||
int digit = sum%10;
|
||||
carry = sum/10;
|
||||
|
||||
ListNode* newnode = new ListNode*(digit);
|
||||
tail->next = newnode;
|
||||
tail = tail->next;
|
||||
|
||||
l1 = (l1!=nullptr) ? l1=>next : nullptr;
|
||||
l2 = (l2!=nullptr) ? l2->next : nullptr;
|
||||
}
|
||||
ListNode* result = dummyhead->next;
|
||||
delete dummyhead;
|
||||
return result;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
The intuition behind this problem kind of reminded me of the CarryLook-Ahead adder (CLA) which I funnily enough know through minecraft builds.
|
||||
its very similar to pen paper additon which starts from least significant bit and we got a seperate carry bit to add it in parallel. A solid solution indeed.
|
||||
Reference in New Issue
Block a user