Leetcode 2 Add Two Numbers

preview_player
Показать описание
Leetcode 2 Add two Numbers, Leetcode 2, Add two Numbers,Leetcode, LinkedList, java solution, Amazon Interview, Google Interview, Java Interview #Leetcode #LeetcodeJavaSolutions #FAANGInterview #Leetcode2 #AddTwoNumbers

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

Optimized using two Mathematica operations:

/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {

int sum=0;
int val1=0;
int val2=0;
int carry=0;
ListNode resultNode= new ListNode(-1);
ListNode temp=resultNode ;

while(l1 !=null || l2!=null )
{
val1= l1==null?0:l1.val;
val2= l2==null?0:l2.val;

sum= carry+val1+val2;
IF - Else Statements in previous code can be replaced with these statements
carry=sum/10;
temp.next=new ListNode(sum%10);

temp=temp.next;
l2= l2==null?null:l2.next;
l1= l1==null?null:l1.next;
}

if (l1 ==null && l2==null && carry>0)
{
temp.next=new ListNode(carry);

}

return resultNode.next;

}
}

pratikshabakrola
Автор

Code explained in the video:

/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {

ListNode result= new ListNode(-1);
ListNode temp=result;
int sum =0;
int carry=0;
int val1=0;
int val2=0;

while (l1!=null || l2 !=null)
{
val1 = l1==null?0:l1.val;
val2 = l2==null?0:l2.val;

sum = carry+ val1+ val2;
carry =0;
if(sum<=9)
{
temp.next=new ListNode(sum);
temp=temp.next;
}else{

temp.next= new ListNode( Integer.parseInt(
temp= temp.next;
carry = Integer.parseInt( ;

}
l1= l1==null? null: l1.next;
l2= l2==null?null: l2.next;
}
if(carry>0)
{
temp.next=new ListNode(carry);
}
return result.next;

}
}

pratikshabakrola
Автор

Awesome.. this is very well explained. keep doing it Thanks

srikanthreddy
Автор

Maam u have perfect knolwegr plz make one dsa series for us

hitpumpworld_khiladi
Автор

Good, make more videoes on leetcode problems....

mayappapujari
join shbcf.ru