英文:
Check if number is divisible by a power of two
问题
Find the highest power of two that divides x
, a 64-bit integer, or return -1.
The zero case is not defined, since it divides any power of two, so your method can return any number.
I tried using the BigInteger.getLowestSetBit()
for this, it returns the right answer but it's far from being optimal.
Example: Input -> output
- 3 -> -1
- 6 -> 1
- 4256 -> 5
英文:
Find the highest power of two that divides x
, a 64-bit integer, or return -1.
The zero case is not defined, since it dives any power of two, so your method can return any number.
I tried using the BigInteger.getLowestSetBit()
for this, it returns the right answer but it's far from being optimal.
Example: Input -> output
- 3 -> -1
- 6 -> 1
- 4256 -> 5
答案1
得分: 5
在 Long
类中,有一个便捷的静态函数 numberOfTrailingZeros
,它几乎实现了你想要的功能,除了在输入不能被 2 整除时会返回 0(而不是 -1)。你可以用不同的方式处理这种情况。例如,扩展 @0x476f72616e 的答案:
if ((num & 0x1) == 0)
return Long.numberOfTrailingZeros(num);
else
return -1;
英文:
In the Long
class, there is a handy static function numberOfTrailingZeros
, which does almost what you want, except that it returns zero (instead of -1) when the input is not divisible by 2. You could handle that case in different ways. For example, extending the answer of @0x476f72616e
if ((num & 0x1) == 0)
return Long.numberOfTrailingZeros(num);
else
return -1;
答案2
得分: 2
一个可能的算法是:(伪代码)
使用一个计数器,将其设置为零,将数字放入一个整数变量 intvar 中
执行以下步骤:
- 右移(整数除以二)-> dividedvar
- 如果 dividedvar * 2 不等于 intvar,则设置 dividedvar = 0 /退出条件/
- 否则(intvar = dividedvar 且 计数器加一)
重复执行以上步骤,直到 dividedvar 不等于 0
尝试一下
英文:
one algorithm may be: (pseudocode)
use a counter set to zero, put number in a var intvar
do{
- shift right (integer divide by two) ->dividedvar
- if dividedvar*2 != intvar then dividedvar = 0 /exit condition/
- else (intvar = dividedvar and counter ++)
}
while dividedvar !=0
try it
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论