您的位置:首页 > 其它

leetcode Power of Two位运算

2015-07-06 11:27 204 查看
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;
				else
					return false;
			}
			n = n / 2;
		}
	}
};


也可以用位运算:

class Solution {
public:
	bool isPowerOfTwo(int n) {
		if (n < 1) return false;
	    return !(n&(n-1));
	}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: