Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- You have two numbers represented by a linked list, where each node contains a single digit. The digits are stored in reverse order, such that the highest order digit is at the head of the list.
- Write a function that adds the two numbers and returns the sum as a linked list.
- Input format:
- First line contains N, number of elements in the first linked list.
- Next line contains N space separated integers, elements of that linked list.
- First line contains M, number of elements in the second linked list.
- Next line contains M space separated integers, elements of that linked list.
- Output format
- Print the sum of the given numbers.
- Sample Input 1
- 3
- 7 1 6
- 3
- 5 9 2
- Sample Output 1
- 2 1 9
- Explanation
- 617 + 295 = 912
- Sample Input 2
- 2
- 4 9
- 2
- 0 5
- Sample Output 2
- 4 4 1
- Explanation
- 94 + 50 = 144
- Sample Input 3
- 2
- 1 0
- 1
- 2
- Sample Output 3
- 3 0
- Explanation
- That is, 01 + 2 = 03. Note that we retain the preceding 0 as well.
- Constraints
- 1 <= M, N <= 10^5
- */
- /*
- class ListNode{
- constructor(val){
- this.val = val;
- this.next = null;
- }
- */
- function getSum(str1,n,str2,m){
- let carry=0,i=0,j=0,str='';
- while(i<n&&j<m){
- let sum=parseInt(str1[i])+parseInt(str2[i])
- +carry;
- carry =parseInt(sum/10);
- sum=parseInt(sum%10);
- str=str+(sum).toString();
- i++;
- j++;
- }
- while(i<n){
- let sum=parseInt(str1[i])+carry;
- carry =parseInt(sum/10);
- sum=parseInt(sum%10);
- str=str+(sum).toString();
- i++;
- }
- while(j<m){
- let sum=parseInt(str2[j])+carry;
- carry =parseInt(sum/10);
- sum=parseInt(sum%10);
- str=str+(sum).toString();
- j++;
- }
- if(carry>0){
- str=str+(carry).toString();
- }
- return str;
- }
- function getFinalList(str){
- let head=null;
- let pointer=null;
- let i=0;
- while(i<str.length){
- const newNode=new ListNode(parseInt(str[i]));
- if(head==null){
- head=newNode;
- pointer=head;
- }else{
- pointer.next=newNode;
- pointer=pointer.next;
- }
- i++;
- }
- return head;
- }
- /**
- * @param {ListNode} head1
- * @param {ListNode} head2
- * @return {ListNode}
- */
- function sumLists1(head1, head2) {
- let str1='',str2='',str='',head=null,ptr;
- ptr=head1;
- while(ptr!=null){
- str1=str1+(ptr.val).toString();
- ptr=ptr.next;
- }
- ptr=head2;
- while(ptr!=null){
- str2=str2+(ptr.val).toString();
- ptr=ptr.next;
- }
- str=getSum(str1,str1.length,str2,str2.length);
- head=getFinalList(str);
- return head;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement