将值分解为2的幂的结果 [英] Decomposing a value into results of powers of two

查看:99
本文介绍了将值分解为2的幂的结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有可能获得作为2的幂的结果的整数?

Is it possible to get the integers that, being results of powers of two, forms a value?

Example: 
129 resolves [1, 128]
77 resolves [1, 4, 8, 64]

我已经考虑过使用Math.log并使用按位比较器进行一次foreach.还有其他更漂亮的解决方案吗?

I already thought about using Math.log and doing also a foreach with a bitwise comparator. Is any other more beautiful solution?

推荐答案

最简单的方法是使用单个位值,从1开始并将该位向左"移位,直到其值大于要检查的值为止,然后进行比较每个位都按该值逐位步进.设置的位可以存储在数组中.

The easiest way is to use a single bit value, starting with 1 and shift that bit 'left' until its value is greater than the value to check, comparing each bit step bitwise with the value. The bits that are set can be stored in an array.

function GetBits(value) {
  var b = 1;
  var res = [];
  while (b <= value) {
    if (b & value) res.push(b);
    b <<= 1;
  }
  return res;
}

console.log(GetBits(129));
console.log(GetBits(77));
console.log(GetBits(255));

由于将位移位视为2的幂,因此可以将当前位值直接推入结果数组.

Since shifting the bit can be seen as a power of 2, you can push the current bit value directly into the result array.

示例

这篇关于将值分解为2的幂的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆