1.2 的幂
bool isPowerOfTwo(int n) { int sum=0; while(n){ if(n&1)sum++; if(sum>1)return false; n>>=1; } if(sum!=0)return true; return false; }
2.4的幂
bool isPowerOfFour(int n) { return (n>0)&&((n&(n-1))==0)&&n%3==1; }
3.位1的个数
int hammingWeight(uint32_t n) { int sum=0; while(n){ if(n&1)sum++; n>>=1; } return sum; }
4.交换数字
vector<int> swapNumbers(vector<int>& numbers) { numbers[0]^=numbers[1]; numbers[1]^=numbers[0]; numbers[0]^=numbers[1]; return numbers; }
5.只出现一次的数字
int singleNumber(vector<int>& nums) { int sum=0; for(int i=0;i<nums.size();i++){ sum^=nums[i]; } return sum; }
6.汉明距离
int hammingDistance(int x, int y) { int p=x^y,sum=0; while(p){ if(p&1)sum++; p>>=1; } return sum; }
7.交替位二进制数
while(n){ if((n&3)==3||(n&3)==0)return false; n>>=1; } return true;
int subsetXORSum(vector<int>& nums) { int psum=0; int ans; for(int i=0;i<(1<<(nums.size()));i++){ ans=0; for(int j=0;j<nums.size();j++){ if(i&(1<<j)){ ans^=nums[j]; } } psum+=ans; } return psum; }
9.两整数之和
int getSum(int a, int b) { return b==0?a:getSum(a^b,(unsigned long long)(a&b)<<1); }
10.插入
int insertBits(int N, int M, int i, int j) { for(int k=i;k<=j;k++){ N&=~((long long)1<<k); } return N|(M<<i); }
标签:return,运算,int,sum,while,vector,numbers From: https://www.cnblogs.com/zhanghx-blogs/p/17162262.html