We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
functionmain(){varn=parseInt(readLine());varunsorted=[];for(varunsorted_i=0;unsorted_i<n;unsorted_i++){unsorted[unsorted_i]=readLine();}// your code goes hereunsorted.sort(function(a,b){if(a.length>b.length){return1;}elseif(a.length===b.length){varaChars=a.split('');varbChars=b.split('');for(variter=0;iter<a.length&&iter<b.length;iter++){varcurrentANum=parseInt(aChars[iter]);varcurrentBNum=parseInt(bChars[iter]);if(currentANum>currentBNum){return1;}elseif(currentANum<currentBNum){return-1;}else{// Do nothing so that we fall to the next character position comparison}}return0;}else{return-1;}});unsorted.forEach(function(currentItem){console.log(currentItem);});}
Basic idea is to do a length comparison first, as the larger string will be a larger number. If they are the same length, then we need to compare their actual values.
Simple doing a comparison between A and B doesn't always work for the really large strings, so instead I iterate through each character in the string to compare their numerical values against each other.
This starts at the beginning of the string, because if this number is bigger than the other, we know the rest of the number is larger too. If both characters are equal, look to the next set of characters to see which is larger.
Iteration stops by the return statement so if we find one is larger than the other, we don't keep looping the entire split arrays.
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Big Sorting
You are viewing a single comment's thread. Return to all comments →
JavaScript Solution:
Basic idea is to do a length comparison first, as the larger string will be a larger number. If they are the same length, then we need to compare their actual values.
Simple doing a comparison between A and B doesn't always work for the really large strings, so instead I iterate through each character in the string to compare their numerical values against each other.
This starts at the beginning of the string, because if this number is bigger than the other, we know the rest of the number is larger too. If both characters are equal, look to the next set of characters to see which is larger.
Iteration stops by the return statement so if we find one is larger than the other, we don't keep looping the entire split arrays.