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

Power of Two

时间:2015-07-08 20:48:12      阅读:97      评论:0      收藏:0      [点我收藏+]

标签:

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

method:

1. recursive:

if x % 2 != 0, return false;

if x == 0, return false;

if x == 1, return true;

else, return isPowerOfTwo(x / 2);

 1 class Solution {
 2 public:
 3     bool isPowerOfTwo(int n) {
 4         if (n == 1) {
 5             return true;
 6         }
 7         if (n == 0 || n % 2 != 0) {
 8             return false;
 9         }
10         return isPowerOfTwo(n / 2);
11     }
12 };

 

2. trick

if x is power of 2, there is only one ‘1‘ in x(bit format). Using x & (x - 1) calculate the count of 1 in x.

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

 

Power of Two

标签:

原文地址:http://www.cnblogs.com/huj690/p/4630965.html

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