Skip to content

Instantly share code, notes, and snippets.

@peZhmanParsaee
Created July 2, 2020 21:20
Show Gist options
  • Save peZhmanParsaee/a9cbc62315694f4b457bc8f9d94099ab to your computer and use it in GitHub Desktop.
Save peZhmanParsaee/a9cbc62315694f4b457bc8f9d94099ab to your computer and use it in GitHub Desktop.
A function in JavaScript that gets a number as a parameter and returns back an array containing powers of two that sum of all equals to the passed number
/**
* @param {number} num - it's a number in radix 10 that indicates summation of power of 2 numbers
* @returns an array containing power of 2 numbers that sum of all is equal to num
*/
export const deconstructPowersOfTwo = (num: number) => {
let decimalArray = [];
const binaryNumberString = num.toString(2);
const reversedBinaryNumber = reverseString(binaryNumberString);
for (let i = 0; i < reversedBinaryNumber.length; i++) {
if (reversedBinaryNumber[i] === '1') {
decimalArray.push(Math.pow(2, i));
}
}
return decimalArray;
};
export const reverseString = (str: string) => {
const reversedStr = str
.split('')
.reverse()
.join('');
return reversedStr;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment