简体   繁体   English

Javascript (ES6) 将数字转换为 2 的幂的字符串数组

[英]Javascript (ES6) convert number into string array of powers of 2

Is there any smart inliner/one-liner (ES6) in transforming a number (integer) into a string array which got the number's bit position of its binary powers (pow(2,x))?是否有任何智能内联/单行(ES6)将数字(整数)转换为字符串数组,该数组获得数字的二进制幂(pow(2,x))的位位置? ie IE

13  =>    ["1","3","4"]    //   (pow(2,1) + pow(2,3)  + pow(2,4))  = 13

If you actually want an array of the powers of 2 which will result in the number, then for 13, you'd want:如果你真的想要一个 2 的幂数组,这将导致数字,那么对于 13,你会想要:

2 ** 0 = 1
2 ** 2 = 4
2 ** 3 = 8
1 + 4 + 8 = 13

That is - [0, 2, 3] are the powers which result in 13.也就是说 - [0, 2, 3]是导致 13 的幂。

.toString(2) turns a number into its binary equivalent, so you can take the elements of that string which are 1s: .toString(2)将一个数字转换为其二进制等价物,因此您可以将该字符串的元素设为 1:

 const num = 13; const arr = []; [...num.toString(2)].reverse().forEach((bit, i) => { if (bit === '1') { arr.push(i); } }); console.log(arr);

Like all JS code, it's possible to squash into one line, but it'd be pretty silly - better to write clean and readable code without regard to line length:像所有 JS 代码一样,可以将其压缩为一行,但这很愚蠢 - 最好编写干净易读的代码而不考虑行长:

 const num = 13; const arr = []; [...num.toString(2)].reverse().forEach((bit, i) => { if (bit === '1') { arr.push(i); } }); console.log(arr);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM