1 题目描述
Given an integer, write a function to determine if it is a power of two.
2 解题思路
采用打表的方式,因为个数不是很多。
采用hashset方式,提高查找效率。
3 其他思路
采用按位与的思想,2的指数次方转化为二进制,只有一位为1,其他位全是0。参考网址:
http://www.bubuko.com/infodetail-953320.html
4 源代码
package com.larry.easy;
import java.util.HashSet;
public class PowerOfTwo {
public boolean isPowerOfTwo(int n) {
//打表
HashSet<Integer> hs = new HashSet<Integer>();
hs.add(1);
hs.add(2);
hs.add(4);
hs.add(8);
hs.add(16);
hs.add(32);
hs.add(64);
hs.add(128);
hs.add(256);
hs.add(512);
hs.add(1024);
hs.add(2048);
hs.add(4096);
hs.add(8192);
hs.add(16384);
hs.add(32768);
hs.add(65536);
hs.add(131072);
hs.add(262144);
hs.add(524288);
hs.add(1048576);
hs.add(2097152);
hs.add(4194304);
hs.add(8388608);
hs.add(16777216);
hs.add(33554432);
hs.add(67108864);
hs.add(134217728);
hs.add(268435456);
hs.add(536870912);
hs.add(1073741824);
boolean ret = hs.contains(n);
return ret;
}
public static void main(String[] args) {
/*System.out.println(Integer.MAX_VALUE);
for(int i = 0; i < 36; i++)
System.out.println("hs.add(" + (int)(Math.pow(2, i)) + ");");*/
}
}