关闭

[leetcode] 231. Power of Two

标签: leetcodeeasy
89人阅读 评论(0) 收藏 举报
分类:

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


Solution 1

Idea: divide n by 2, and check the residual. 

class Solution {
public:
    bool isPowerOfTwo(int n) {
        while (n!=0 && n%2==0){
            n = n/2;
        }
        return n==1;
        
    }
};

Solution 2

Idea: 1 -- 1, 2 -- 10, 4 -- 100,... the highest bits are all 1. If minus 1, the left bit become 0 ,and others become 1s. Do bit logic and, should be 0;

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



0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:9701次
    • 积分:632
    • 等级:
    • 排名:千里之外
    • 原创:31篇
    • 转载:150篇
    • 译文:0篇
    • 评论:0条
    文章分类