LeetCode 2. Add Two Numbers [Algorithm + Code Explained ] Best Solution

preview_player
Показать описание
One of the most frequently asked coding interview questions on Arrays in companies like Google, Facebook, Amazon, LinkedIn, Microsoft, Uber, Apple, Adobe etc.

LeetCode : Add Two Numbers

Question - You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.

You may assume the two numbers do not contain any leading zero, except the number 0 itself.

Example:

Input: (2 - 4 - 3) + (5 - 6 - 4)
Output: 7 - 0 - 8
Explanation: 342 + 465 = 807

Рекомендации по теме
Комментарии
Автор

Great explanation, A bit optimization in above code, We are adding only single-digit of LinkedList, thus we can tell the carry would not be greater than 1(Maximum 1 digit calculation would be (9+9) which 18 and carry is 1).

if(sum >= 10)
{
carry = 1;
sum = sum%10;
}



And also we can put the condition only perform carry operation when the sum is greater than or equal to 10.

hiteshmoorjani
Автор

Awesome Jayati your concept is so clear how the new node is created and pointer is moved to the next node. Thank you for a good and simple approach. Keep this good work.

AbhinavKumar-dref
Автор

You explain these concepts really well!

ryanbennett
Автор

Great videos, It would be nice if there is a link to the slide shown in 2:20

mkiruba
Автор

5722765 - 3000 what type of algorithm is this? Please help!

mohammedsaleh
Автор

Why are we returning sumHead.next and not sumHead?

indranilthakur
Автор

perfect example of beauty with brain...😅..thanks for the concept

gauravshukla
Автор

Jitne log amswer nhi deak rahe honge ushe zayda to jo padha rahi hai use deak rahe hone

😅😅😅

imagination
Автор

implementation in ruby
```
def add_two_numbers(l1, l2)
pointer_to_head = ListNode.new # dummy
tail = pointer_to_head
local_sum = 0
until l1.nil? && l2.nil? && local_sum == 0
if l1
local_sum += l1.val
l1 = l1.next
end
if l2
local_sum += l2.val
l2 = l2.next
end
tail.next = ListNode.new local_sum % 10 # hook up
local_sum = local_sum / 10 # serves as a carryover
tail = tail.next # reassign running pointer to the newly created node
end
pointer_to_head.next
end

```

laptewstein
visit shbcf.ru