临近期末了,解题还是会继续坚持的。
今天的题就一道有点难度,其他都挺好刷的!
位运算之异或记住:同为0,异位1;
力扣练习题:
136. 只出现一次的数字https://leetcode-cn.com/problems/single-number/
https://leetcode-cn.com/problems/single-number/
解题思路:
全部数字异或一遍,相同的就变为0了,剩下的就是所要求解的数;
int singleNumber(int* nums, int numsSize){
int num=0;
for(int i=0;i<numsSize;i++)
{
num=num^nums[i];
}
return num;
}
190. 颠倒二进制位https://leetcode-cn.com/problems/reverse-bits/
https://leetcode-cn.com/problems/reverse-bits/
解题思路:
先定义一个无符号整型变量,其他类型会出错;
每次都取最低位进行与操作然后进行存起来
uint32_t reverseBits(uint32_t n) {
unsigned int num;
for(int i=0;i<32&&n>0;i++)
{
num=num|((n&1)<<(31-i));
n=n>>1;
}
return num;
}
461. 汉明距离https://leetcode-cn.com/problems/hamming-distance/
https://leetcode-cn.com/problems/hamming-distance/
解题思路:
现将两个数进行异或运算,然后对每一位进行判断。
int hammingDistance(int x, int y){
int num=x^y,sum=0;
while(num)
{
sum=sum+(num&1);
num=num>>1;
}
return sum;
}
1486. 数组异或操作https://leetcode-cn.com/problems/xor-operation-in-an-array/
https://leetcode-cn.com/problems/xor-operation-in-an-array/
解题思路:
没啥好说的,看题干就可以解决
int xorOperation(int n, int start){
int sum=0,num=start;
while(num<=(start+2*(n-1)))
{
sum=sum^num;
num=num+2;
}
return sum;
}
477. 汉明距离总和https://leetcode-cn.com/problems/total-hamming-distance/
https://leetcode-cn.com/problems/total-hamming-distance/
解题思路:
只能说暴力解不了,看官方题解比较好理解
int totalHammingDistance(int* nums, int numsSize){
int sum=0,num=0;
for(int i=0;i<30;i++)
{
int num=0;
for(int j=0;j<numsSize;j++)
{
num=num+((nums[j]>>i)&1);
}
sum=sum+num*(numsSize-num);
}
return sum;
}
1720. 解码异或后的数组https://leetcode-cn.com/problems/decode-xored-array/
https://leetcode-cn.com/problems/decode-xored-array/
解题思路:
看题目就能看懂,没啥好说的
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
int* decode(int* encoded, int encodedSize, int first, int* returnSize){
int *array=(int *)malloc(sizeof(int)*(encodedSize+1));
array[0]=first;
for(int i=1;i<encodedSize+1;i++)
{
array[i]=array[i-1]^encoded[i-1];
}
*returnSize=encodedSize+1;
return array;
}