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

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

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

package testPass; /** *for positive integer only! *@author 孙如意 rysun@qq.com */ 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; } }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值