基础位运算

基础知识点:

1.判断2的幂 n&(n-1)==0

2.每次减一处理 n&(n-1)

3.判断出现1次次数的数 x^0==x,x^x==0,a^b=c则a=b^c,b=a^c

力扣练习题:

136.只出现一次的数字

cpp 复制代码
class Solution {
public:
    int singleNumber(vector<int>& nums) {
        int result=0;
        for(int i=0;i<nums.size();i++)
        {
            result^=nums[i];
        }
        return result;
    }
};

191.位1的个数

cpp 复制代码
class Solution {
public:
    int hammingWeight(uint32_t n) {
        int ret = 0;
        for (int i = 0; i < 32; i++) {
            if (n & (1 << i)) {
                ret++;
            }
        }
        return ret;
    }
};

或者直接调用函数(return __builtin_popcount(n);)

231.2的幂

cpp 复制代码
class Solution {
public:
    bool isPowerOfTwo(int n) {
        return (n>0) && (n & (n-1))==0 ;
    }
};

342.4的幂

cpp 复制代码
class Solution {
public:
    bool isPowerOfFour(int n) {
        if(n>0 && (n&(n-1))==0 && n%3==1)
        {
            return true;
        }
        else return false;
    }
};

476.数字的补数()

cpp 复制代码
class Solution {
public:
    int findComplement(int num) {
        //a^b=c a=b^c 已知a和b位相反 所以先求出c=111............
        int num1=1;
        while(num1<num)
        {
            num1<<=1,num1++;
        }//找到比num大全为1的数 
        return num1^num;
    }
};
相关推荐
黑岚樱梦41 分钟前
代码随想录打卡day23:435.无重叠区间
算法
Kuo-Teng1 小时前
Leetcode438. 找到字符串中所有字母异位词
java·算法·leetcode
gihigo19982 小时前
MATLAB使用遗传算法解决车间资源分配动态调度问题
算法·matlab
墨染点香2 小时前
LeetCode 刷题【138. 随机链表的复制】
算法·leetcode·链表
却道天凉_好个秋2 小时前
目标检测算法与原理(一):迁移学习
算法·目标检测·迁移学习
兮山与3 小时前
算法24.0
算法
晓北斗NorSnow3 小时前
机器学习核心算法与学习资源解析
学习·算法·机器学习
hans汉斯4 小时前
【计算机科学与应用】基于BERT与DeepSeek大模型的智能舆论监控系统设计
大数据·人工智能·深度学习·算法·自然语言处理·bert·去噪
多喝开水少熬夜5 小时前
损失函数系列:focal-Dice-vgg
图像处理·python·算法·大模型·llm