Skip to content
Advertisement

converting number bases to string using a recursive function javascript

I’m trying to write a recursive function that takes two parameters – an integer input, n, and an integer base, m – and returns a string representation of the number in Base m. I’m stuck can someone help?

const toStr = (n, base) => {
   //when no remainder return 1
  if(n % base === 0) return 1;
  if(n % base >= 1){
   return toStr(Math.floor(n/base))+(n % base);
  }
  return " ";
}


toStr(199, 10) //'199'
toStr(14, 8)//'16'
toStr(30, 2)//'11110'

Advertisement

Answer

You forgot to include base in recursive call

And to reduce complexity, the base case of this recursion call is to check whether n is zero, then return empty string to concat with the returned from upper stack call

const toStr = (n, base) => {
  //when no remainder return 1
  if (!n) {
    return "";
  }
  return toStr(Math.floor(n / base), base) + (n % base);
};

console.log(toStr(199, 10)); //'199'
console.log(toStr(14, 8)); //'16'
console.log(toStr(30, 2)); //'11110'
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement