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

Leetcode 231. Power of Two

时间:2016-08-02 01:12:07      阅读:124      评论:0      收藏:0      [点我收藏+]

标签:

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

 

题目大意:判断一个数是否是2的指数次。

思路:如果一个数是2的指数次,那么它对应的二进制数中只有一个1;利用位运算即可解决。‘

 1 class Solution {
 2 public:
 3     bool isPowerOfTwo(int n) {
 4         int k = 0;
 5         while(n > 0){
 6             if(n & 1)
 7                 k++;
 8             n >>= 1;
 9         }
10         if(k == 1)
11             return true;
12         return false;
13     }
14 };

 

Leetcode 231. Power of Two

标签:

原文地址:http://www.cnblogs.com/qinduanyinghua/p/5727673.html

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