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

leetcode_Power of Two_easy

时间:2017-05-02 11:57:02      阅读:160      评论:0      收藏:0      [点我收藏+]

标签:line   min   write   span   size   pre   cti   font   amp   

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

题目意思:推断某个数是否是2的幂。

方法:直接进行bit运算,推断是否这个数二进制位里有且仅有一个1。

class Solution {
public:
    bool isPowerOfTwo(int n) {
        int c=0;
        while(n!=0)
        {
            c+=1&n;
            if(c>1)
                return false;
            n>>=1;
        }
        if(c==1)
            return true;
        else
            return false;
    }
};



leetcode_Power of Two_easy

标签:line   min   write   span   size   pre   cti   font   amp   

原文地址:http://www.cnblogs.com/slgkaifa/p/6795118.html

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