首页 > 其他 > 详细

231 Power of Two

时间:2015-09-08 09:27:28      阅读:216      评论:0      收藏:0      [点我收藏+]

Given an integer, write a function to determine if it is a power of two.


Java code:(两种方法,第二种方法很妙,用到了bit wise )

第二种方法解题思路:

如果一个整数是2的幂,那么它的二进制形式最高位为1,其余各位为0

等价于:n & (n - 1) = 0,且n > 0

 1 /*
 2 * 1 = 2^0, true
 3 * */
 4 public class PowerOfTwo {
 5     public static void main(String[] args) {
 6         int x =1023;
 7         boolean y = isPowerOfTwo(x);
 8         System.out.println(y);
 9     }
10 
11     /*
12     * method1
13     */
14     public static boolean isPowerOfTwo(int n) {
15         if(n <= 0 ) {return false;}
16         while(n %2 == 0 ) {
17                 n = n/2;
18         }
19         if(n==1) {return true;}
20         return false;
21     }
22 
23     /*
24     * method2
25     * */
26     public static boolean isPowerOfTwo(int n) {
27         int x = n & (n-1);
28         return (n > 0) & (x==0);
29     }
30 }

Reference:

1. http://bookshadow.com/weblog/2015/07/06/leetcode-power-of-two/

 

231 Power of Two

原文:http://www.cnblogs.com/anne-vista/p/4790529.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!