class Solution {
public:
bool isPowerOfTwo(int n) {
if(n==1)return true;
while(n){
if(n%2==0){
n=n/2;
if(n==1||n==2)return true;
}
//奇数
else{
return false;
}
}
return false;
}
};
若n是2的幂,那么只有最左是1,与n-1相与为0
class Solution {
public:
bool isPowerOfTwo(int n) {
if(n<=0)return false;
if((n&(n-1))==0)return true;
return false;
}
};
、、、、、、、、、、
位运算
与 & 同1为1
或 | 有1为1
异或 ^ 不同为1,可无第三方交换数字
//只出现一次的数字
class Solution {
public:
int singleNumber(vector<int>& nums) {
int n=nums[0];
for(int i=1;i<nums.size();i++){
n=nums[i]^n;
}
return n;
}
};
取反 ~
左移 《 末尾补0,数值*2
右移 》 负数补1,非负补0,数值/2