基础位运算

基础知识点:

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;
    }
};
相关推荐
weixin_4684668525 分钟前
目标识别精度指标与IoU及置信度关系辨析
人工智能·深度学习·算法·yolo·图像识别·目标识别·调参
多恩Stone29 分钟前
【3D AICG 系列-8】PartUV 流程图详解
人工智能·算法·3d·aigc·流程图
铸人33 分钟前
再论自然数全加和-质数的规律
数学·算法·数论·复数
二年级程序员34 分钟前
一篇文章掌握“顺序表”
c语言·数据结构
历程里程碑2 小时前
Linux22 文件系统
linux·运维·c语言·开发语言·数据结构·c++·算法
YGGP3 小时前
【Golang】LeetCode 128. 最长连续序列
leetcode
你撅嘴真丑9 小时前
第九章-数字三角形
算法
uesowys9 小时前
Apache Spark算法开发指导-One-vs-Rest classifier
人工智能·算法·spark
ValhallaCoder9 小时前
hot100-二叉树I
数据结构·python·算法·二叉树
董董灿是个攻城狮9 小时前
AI 视觉连载1:像素
算法