首页 > 其他 > 详细

leetcode 231: Power of Two

时间:2015-07-07 07:04:31      阅读:97      评论:0      收藏:0      [点我收藏+]

Power of Two

Total Accepted: 3596 Total Submissions: 11779

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

Credits:
Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.

[思路]

如果是power of two, 则2进制表达中,有且仅有一个1.  可以通过移位来数1的个数, 这里用了一个巧妙的办法, 即判断   N & (N-1) 是否为0.

[CODE]

public class Solution {
    public boolean isPowerOfTwo(int n) {
       return n > 0 && ((n & (n - 1)) == 0 );
    }
}


版权声明:本文为博主原创文章,未经博主允许不得转载。

leetcode 231: Power of Two

原文:http://blog.csdn.net/xudli/article/details/46784163

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