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.
TypeScript binary converter function (The hard way lol)
functionbinary_convert(n:number):string{leti:number=0;letbinary:string='';letmax:number=0;while(Math.pow(2,i)<n){//Save the largest number for considering total length of binarymax=i+1;i++;}// console.log(i);// Divide it until every element is turned to binary (No remainder left)while(n>0&&i>0){// Binary is larger or equal to remainder, modulo and add 1 to the binary stringif(Math.pow(2,i-1)<=n){n=n%Math.pow(2,i-1);binary+='1';}// Number bigger than largest binary : skip the current binaryelse{binary+='0';}// Continue to smaller binaryi--;}// console.log('max =' + max)// If no remainder left, Add zeroes at the right until full lengthwhile(binary.length<max){binary+='0';}// console.log('binary = ' + binary)returnbinary}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Day 10: Binary Numbers
You are viewing a single comment's thread. Return to all comments →
TypeScript binary converter function (The hard way lol)