【leetcode】位运算刷题记录

【leetcode】位运算刷题记录


前言

本文是基于leetcode位运算例题的学习记录


LCR 133. 位 1 的个数

链接
两种方法都是很常见的位运算,记忆一下

class Solution {
public:
    int hammingWeight(uint32_t n) {
        int ans = 0;
        while(n != 0)
        {
            if(n & 1) ans ++;
            n >>= 1;
        }
        return ans;
    }
};
class Solution {
public:
    int hammingWeight(uint32_t n) {
        int res = 0;
        while(n != 0)
        {
            res ++;
            n &= n - 1;
        }
        return res;
    }
};

LCR 134. Pow(x, n)

链接
模板题,值得一提的是,n的值得给long变量,否则会发生溢出

class Solution {
public:
    double myPow(double x, int n) {
        if(x == 0.0f)return 0.0;
        long b = n;
        double res = 1.0;
        if(b < 0)
        {
            x = 1 / x;
            b = -b;
        }
        while(b > 0)
        {
            if(b & 1)res *= x;
            x *= x;
            b >>= 1;
        }
        return res;
    }
};

LCR 177. 撞色搭配

链接
没写出来,知道要用异或运算但是不记得怎么把x和y分开了,枯
题解中这张图应该能很好解释了:
Alt

class Solution {
public:
    vector<int> sockCollocation(vector<int>& sockets) {
        int x = 0, y = 0, n = 0, m = 1;
        for(int num : sockets)      // 1. 遍历异或
            n ^= num;
        while((n & m) == 0)         // 2. 循环左移,计算 m
            m <<= 1;
        for(int num : sockets) {    // 3. 遍历 sockets 分组
            if(num & m) x ^= num;   // 4. 当 num & m != 0
            else y ^= num;          // 4. 当 num & m == 0
        }
        return vector<int> {x, y};  // 5. 返回出现一次的数字
    }
};

作者:Krahets
链接:https://leetcode.cn/problems/shu-zu-zhong-shu-zi-chu-xian-de-ci-shu-lcof/solutions/572857/jian-zhi-offer-56-i-shu-zu-zhong-shu-zi-tykom/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

LCR 178. 训练计划 VI

偷看了一眼题解,自己写出来了,嘿嘿
链接
题解
Alt

class Solution {
public:
    int trainingPlan(vector<int>& actions) {
        unsigned int bit = 1 << 31;
        int res = 0;
        for(int i = 31; i >= 0; i -- )
        {
            int bitSum = 0;
            for(auto num:actions)
            {
                if(num & bit)bitSum ++;
            }
            res += (bitSum % 3) << i;
            bit >>= 1;
        }
        return res;
    }
};

LCR 190. 加密运算

皮一下~

class Solution {
public:
    int encryptionCalculate(int dataA, int dataB) {
        return dataA + dataB;
    }
};
class Solution {
public:
    int encryptionCalculate(int dataA, int dataB) {
        while(dataB)
        {
            int dataC = (dataB & dataA) << 1;
            dataA ^= dataB;
            dataB = dataC;
        }
        return dataA;
    }
};
  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值