检查数字是否可以被2的某个幂整除

huangapple go评论73阅读模式
英文:

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 中
执行以下步骤:

  1. 右移(整数除以二)-> dividedvar
  2. 如果 dividedvar * 2 不等于 intvar,则设置 dividedvar = 0 /退出条件/
  3. 否则(intvar = dividedvar 且 计数器加一)

重复执行以上步骤,直到 dividedvar 不等于 0

尝试一下

英文:

one algorithm may be: (pseudocode)

use a counter set to zero, put number in a var intvar
do{

  1. shift right (integer divide by two) ->dividedvar
  2. if dividedvar*2 != intvar then dividedvar = 0 /exit condition/
  3. else (intvar = dividedvar and counter ++)
    }
    while dividedvar !=0

try it

huangapple
  • 本文由 发表于 2020年8月25日 01:15:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/63565720.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定