天天看点

怎样知道一个数字是不是2的乘方?

回答了上一篇日志中的一个问题:怎样知道一个数字是不是2的乘方?

在网上搜索了一下,自己总结后,整理出三个方法,代码如下:

package testPass;

/**

*for positive integer only!

*@author 孙如意 [email protected]

*/

public class IsPowerOfTwo {

public static void main (String args[]){

System.out.println("the method of regular expersion: 128 is a power of 2 ? " + method1(128));

System.out.println("the method of bit operation: 128 is a power of 2 ? " + method2(128));

System.out.println("the method of mod operation: 128 is a power of 2 ? " + method3(128));

}

/**

* based on regular expression

* @param num

* @return wheather the num is a power of two

*/

public static boolean method1(Integer num){

String binNum = Integer.toBinaryString(num);

//a number which is a power of 2 in binary has only one 1 and starts with it

return binNum.matches("10*");

}

/**

* based on bit operation

* @param num

* @return wheather the num is a power of two

*/

public static boolean method2(Integer num) {

if ((num & (num-1)) == 0) {

return true;

}

return false;

}

/**

* based on mod operation

* @param num

* @return wheather the num is a power of two

*/

public static boolean method3 (Integer num) {

if(num > 0){

while(num > 0){

if (num % 2 == 1) {

return false;

}else {

num /= 2;

if(num == 1 ) {

return true;

}

}

}

}

return false;

}

}