如何检查数字是否是2的幂
时间:2020-02-23 14:34:15 来源:igfitidea点击:
有许多方法检查数字是否为2的幂
方法1:
这是非常简单和直接的方法。
- 运行一小时循环,如果n是偶数,则检查条件(n%2 == 0)。
- 如果甚至在每次迭代中也将其划分为2.
- 当你离开时循环和n等于1时,数字是2的幂
- 如果数字不等于1,则Number不是2的幂
public static boolean powerOfTwoGeneral(int n)
{
while(n%2==0)
{
n=n/2;
}
if(n==1)
{
return true;
}
else
{
return false;
}
}
方法2:
我们可以使用按位和运算符来检查数字是否为2的幂
public static boolean powerOfTwoBitwise(int n)
{
return (n & n-1)==0;
}
检查数量是否为2的功率是一个非常简单的方法。
让我们看看它是如何工作的。
让我们说n是8.它的二进制表示将是:1000。
二进制数量为7将是:0111. 1 0 0 0 0&0 1 1 1 1 - 0 0 0 0 0 ---如果数字为2,那么它只将一位设置为"1"。
例如:8:1000 32:100000
同样在检查7和31的二进制形式时,它将将所有位设置为"1"7:111 31:11111,因此如果在n和n-1上应用按位和运算符,结果是0.它意味着数字是2的幂
Java程序检查号码是否为二号:
package org.igi.theitroad;
public class PowerOfTwoMain {
public static void main(String[] args) {
System.out.println("128 is power of two : "+powerOfTwoGeneral(128));
System.out.println("64 is power of two : "+powerOfTwoBitwise(64));
System.out.println("22 is power of two : "+powerOfTwoBitwise(22));
System.out.println("22 is power of two : "+powerOfTwoGeneral(22));
}
//Approach 1
public static boolean powerOfTwoGeneral(int n)
{
while(n%2==0)
{
n=n/2;
}
if(n==1)
{
return true;
}
else
{
return false;
}
}
//Approach 2
public static boolean powerOfTwoBitwise(int n)
{
return (n & n-1)==0;
}
}
当我们运行上面的代码时,我们将得到以下结果
128 is power of two : true 64 is power of two : true 22 is power of two : false 324 is power of two : false

