Power of Two

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)) + ");");*/
	}
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值