I wanted to write a recursive function in js to calc the binary represenation of a decimal number.
I did manage to solve this by :
var t = (function f(n, s)
{
return((s = (n % 2) + s) && (n == 0)) ? s : f(Math.floor(n / 2), s);
})(4, '');
console.log(t);
Fiddle:
However, I can't get rid of the leading zero.
So if I execute the IIFE with 7 it yields : 0111
and I want 111
.
How can I get rid of the leading 0
?
(without string replace solution please. I want to keep it as much elegant as I can.. and I know I can do alert(Number(234).toString(2))
but this question is tagged as recursion.)
I wanted to write a recursive function in js to calc the binary represenation of a decimal number.
I did manage to solve this by :
var t = (function f(n, s)
{
return((s = (n % 2) + s) && (n == 0)) ? s : f(Math.floor(n / 2), s);
})(4, '');
console.log(t);
Fiddle: http://jsbin./ihezev/3/edit
However, I can't get rid of the leading zero.
So if I execute the IIFE with 7 it yields : 0111
and I want 111
.
How can I get rid of the leading 0
?
(without string replace solution please. I want to keep it as much elegant as I can.. and I know I can do alert(Number(234).toString(2))
but this question is tagged as recursion.)
5 Answers
Reset to default 4Here's a clean one I ported from python
const decToBi = num => num === 0 ? 0 : num % 2 + 10 * decToBi(Math.floor(num / 2));
console.log(decToBi(10)); //1010
A little bit changed but still elegant:
var t = (function f(n, s) {
return n === 0 ? s || "0" : f(~~(n / 2), (n % 2) + s);
})(7, ""); // "111"
function base10ToString(num, str = "") {
if (num === 0) {
return str;
}
if (num % 2 === 0) str = "0" + str;
else str = "1" + str;
return base10ToString(Math.floor(num / 2), str);
}
console.log(base10ToString(7));
You'll need to pass a parameter which represents whether you've produced a 1
yet. Whilst that parameter is false
, you don't produce anything for a 0
.
function binaryConversion(num) {
if (num === 0) {
return "";
}
return binaryConversion(Math.floor(num / 2)) + (num % 2).toString();
}
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744716793a4589667.html
评论列表(0条)