码迷,mamicode.com
首页 > 其他好文 > 详细

*Power of Two

时间:2015-07-30 00:20:23      阅读:103      评论:0      收藏:0      [点我收藏+]

标签:

题目

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

 

解题思路:

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

 

code: 

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

 

reference: http://blog.csdn.net/xudli/article/details/46784163

*Power of Two

标签:

原文地址:http://www.cnblogs.com/hygeia/p/4687800.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!