问题:https://leetcode.com/PRoblems/power-of-two/?tab=Description Given an integer, write a function to determine if it is a power of two. 给定一个数,判断它是不是2的幂数。 分析:二进制来说,2的幂数都是首位是1,其他位是0。所以用n&(n-1)是否为0可以判断。 C++中&&是且,&是按位与。 C++代码:
class Solution {public: bool isPowerOfTwo(int n) { return (n>0) && ((n&(n-1))==0);//&&是且的意思,&是按位与。 }};新闻热点
疑难解答