首页 > 其他 > 详细

Power Of Two

时间:2016-02-02 22:21:27      阅读:174      评论:0      收藏:0      [点我收藏+]

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

我的解决方式:

好久不刷了,没感觉,这个解决方式比较差,下面有一个比较好的解决办法:

 

public class Solution {
    public boolean isPowerOfTwo(int n) {
            if (1 == n) {
            return true;
        }
        int remainder = 0;    // 余数
        int result = n;        //
        while (0 == remainder && 0 < result) {
            remainder = result%2;
            result = result/2;
            if (0 == remainder && 1 == result) {
                return true;
            }
        }
        return false;
    }
}

看到是2的幂,脑子里有寻找规律的想法,但是没有仔细思考。下方用的二进制的方式 & 为位运算符

public static boolean isPowerOfTwo(int n) {
         return n < 1 ? false : (n & (n - 1)) == 0 ? true : false;
    }

 

Power Of Two

原文:http://www.cnblogs.com/tf-Y/p/5178579.html

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