leetcode Power of Two位运算

来源:互联网 发布:代帮上传淘宝宝贝 编辑:程序博客网 时间:2024/06/03 22:50

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

Credits:
Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.

Show Tags

可以直接做:

class Solution {public:bool isPowerOfTwo(int n) {if (n < 1) return false;int res;while (n>0){res = n % 2;if (res != 0){if (n == 1)return true;elsereturn false;}n = n / 2;}}};

也可以用位运算:

class Solution {public:bool isPowerOfTwo(int n) {if (n < 1) return false;    return !(n&(n-1));}};



0 0