admin管理员组文章数量:1389829
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();
}
本文标签: recursionDecimal to binary recursive function in JavaScriptStack Overflow
版权声明:本文标题:recursion - Decimal to binary recursive function in JavaScript - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744716793a2621452.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论