简体   繁体   中英

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))? 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 ** 0 = 1
2 ** 2 = 4
2 ** 3 = 8
1 + 4 + 8 = 13

That is - [0, 2, 3] are the powers which result in 13.

.toString(2) turns a number into its binary equivalent, so you can take the elements of that string which are 1s:

 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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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