基础位运算

基础知识点:

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;
    }
};
相关推荐
沐苏瑶19 小时前
Java 搜索型数据结构全解:二叉搜索树、Map/Set 体系与哈希表
java·数据结构·算法
ccLianLian19 小时前
深度学习·DDPM
数据结构
ZoeJoy820 小时前
算法筑基(二):搜索算法——从线性查找到图搜索,精准定位数据
算法·哈希算法·图搜索算法
Alicx.20 小时前
dfs由易到难
算法·蓝桥杯·宽度优先
_日拱一卒20 小时前
LeetCode:找到字符串中的所有字母异位词
算法·leetcode
云泽80821 小时前
深入 AVL 树:原理剖析、旋转算法与性能评估
数据结构·c++·算法
Wilber的技术分享1 天前
【LeetCode高频手撕题 2】面试中常见的手撕算法题(小红书)
笔记·算法·leetcode·面试
邪神与厨二病1 天前
Problem L. ZZUPC
c++·数学·算法·前缀和
梯度下降中1 天前
LoRA原理精讲
人工智能·算法·机器学习
IronMurphy1 天前
【算法三十一】46. 全排列
算法·leetcode·职场和发展