'Given a non-negative integer, find the indexes of all the bits which are set to 1
Here is what I'm doing:
function getIndexes(n) {
return n
.toString(2)
.split("")
.map((c, i) => [c, i])
.filter(([c, _]) => c == "1")
.map(([_, i]) => i)
;
}
console.log(getIndexes(6));
console.log(getIndexes(7));
console.log(getIndexes(42));
Explanation:
- Convert the input number into a binary string
- Convert the binary string into an array of characters
- Map each character to a
[character, index]tuple - Filter (keep only) the tuples whose character is
"1" - Map each tuple to the index of that tuple
It feels a bit of an overkill.
Is there a more standard way to achieve that?
I care less about performance and more about using something cleaner and/or custom.
Thanks!
Solution 1:[1]
If I well understood what you want to achieve, here is an alternative solution:
function getIndexes(n) {
const result = [];
const long_n = BigInt(n);
for(let i = 0n; i < 64n; ++i) {
if((long_n >> i) & 1n) result.push(Number(i));
}
return result;
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
