【简单】算法nodeJs:求int型正整数在内存中存储时1的个数

58 阅读1分钟

描述

对于给定的 int 型的十进制正整数 n ,统计其在内存中存储时 1 的个数。换句话说,即统计其二进制表示中 1 的个数。

输入描述:

在一行上输入一个整数 n(0≦n<2的31次方) ,代表给定的数字。

输出描述:

在一行上输出一个整数,代表 n 的二进制表示中 1 的个数。

const rl = require("readline").createInterface({ input: process.stdin });
var iter = rl[Symbol.asyncIterator]();
const readline = async () => (await iter.next()).value;

void (async function () {
    // Write your code here
    while ((line = await readline())) {
        const binaryNum = Number(line).toString(2);
        const newArr = binaryNum.split("").filter((i) => i === "1");
        console.log(newArr.length);
    }
})();

Number.prototype.toString()

toString(radix)
  • radix 可选

  • 一个整数,范围在 2 到 36 之间,用于指定表示数字值的基数。默认为 10。