首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >底座10至基地2转换器

底座10至基地2转换器
EN

Stack Overflow用户
提问于 2014-01-25 16:51:55
回答 2查看 2K关注 0票数 1

我试着建造一个基地10到基地2转换器..。

代码语言:javascript
复制
  var baseTen = window.prompt("Put a number from Base 10 to convert to base 2");
    var baseTwo = [];
    var num = baseTen;
    var getBinary = function () {
        baseTwo.reverse();
        for (var i = 0; i <= baseTwo.length - 1; i++) {
            document.write(baseTwo[i]);
        }
    };

    var divide = function () {
        while ( num > 0 ) {
            if (num % 2 === 0) {
                baseTwo.push(0);
                num /= 2;
            } else {
                baseTwo.push(1);
                num /= 2;
            }
      }  
        getBinary();
    };

    divide();

我有一个问题,though...when,我运行它打印的无限的"1"s :\

我似乎无法在while循环中找到正确的条件,使其在"num“不能被除以的正确时间停止,当达到零时,anymore...it需要停止。但我想不出办法。我们会感谢你的帮助。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2014-01-25 16:57:55

在这一行:

代码语言:javascript
复制
num /= 2;

你可能没有得到整数。使用Math.floor:

代码语言:javascript
复制
num = Math.floor(num/2);
票数 2
EN

Stack Overflow用户

发布于 2017-04-12 16:49:14

Javascript中base10到base2转换的清洁递归方法

我在做Hacke 30天的编码挑战,在第10个问题上有这个转换问题。就这样吧。

代码语言:javascript
复制
// @author Tarandeep Singh :: Created recursive converter from base 10 to base 2 
// @date : 2017-04-11
// Convert Base 10 to Base 2, We should reverse the output 
// For Example base10to2(10) = "0101" just do res = base10to2(10).split('').reverse().join();
function base10to2(val, res = '') {
  if (val >= 2) {
    res += '' + val % 2;
    return base10to2(val = Math.floor(val / 2), res);
  } else {
    res += '' + 1
    return res;
  }
}

// Well not needed in this case since we just want to count consecutive 1's but still :) 

let n = 13;

var result = base10to2(n).split('').reverse().join();
document.write(`Converting ${n} into Base2 is ${result}`);

另外,您还可以使用数字的toString方法来完成此操作。

就像let n = 13; console.log(n.toString(2));一样,这也是可行的。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/21353330

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档