回答了上一篇日志中的一個問題:怎樣知道一個數字是不是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;
}
}