Power of Two

来源:互联网 发布:跟兄弟连学php.pdf下载 编辑:程序博客网 时间:2024/06/10 19:49

https://leetcode.com/problems/power-of-two/

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

数字 2^n 是大于0的,而且等于1左移n位得到的数字,所以2^n与2^n-1 相与运算得到0.

bool isPowerOfTwo(int n) {    if(n <= 0)        return false;    if((n & (n-1)) == 0)        return true;    return false;}
bool isPowerOfTwo(int n) {    return n > 0 && !(n & (n-1));}
0 0
原创粉丝点击