`
meikebo
  • 浏览: 15960 次
社区版块
存档分类
最新评论

判断一个数是不是2的阶次方数

    博客分类:
  • JAVA
阅读更多
方法一:
package com.judge;

public class DevideTwo {
	
	public static boolean isDeTwo(int n)
	{
		float tem = (float)n;
		while(true)
		{
			tem=tem/2;
			if(tem<2.0)
				break;
		}
		if(tem==1.0)
			return true;
		else
			return false;
	}
	
	public static void main(String[] args)
	{
		System.out.println(isDeTwo(256));
	}

}


方法二:(最好方法)
package com.judge;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class ExcellectDevTwo {
	
	public static int getData() throws IOException
	{
		BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
		return Integer.valueOf(reader.readLine());
	}
	
	public static boolean isDevTwo(int n)
	{
		if((n&(n-1))==0&&(n!=0))
			return true;
		else
			return false;
	}
	
	public static void main(String[] args)
	{
		try {
			System.out.println(isDevTwo(getData()));
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics