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?
JavaScript
x
14
14
1
const toStr = (n, base) => {
2
//when no remainder return 1
3
if(n % base === 0) return 1;
4
if(n % base >= 1){
5
return toStr(Math.floor(n/base))+(n % base);
6
}
7
return " ";
8
}
9
10
11
toStr(199, 10) //'199'
12
toStr(14, 8)//'16'
13
toStr(30, 2)//'11110'
14
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
JavaScript
1
11
11
1
const toStr = (n, base) => {
2
//when no remainder return 1
3
if (!n) {
4
return "";
5
}
6
return toStr(Math.floor(n / base), base) + (n % base);
7
};
8
9
console.log(toStr(199, 10)); //'199'
10
console.log(toStr(14, 8)); //'16'
11
console.log(toStr(30, 2)); //'11110'