算法5:位运算


没写代码的题,其链接点开都是有代码的。开始前请思考下图:
在这里插入图片描述

小试牛刀

位1的个数

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

比特位计数

class Solution {
public:
    vector<int> countBits(int n) {
        vector<int> res(n + 1);
        for (int i = 0; i < n + 1; ++i) {
            res[i] = count(i);
        }
        return res;
    }
    int count(int n) {
        int res = 0;
        while (n) {
            n &= n - 1;
            res++;
        }
        return res;
    }
};

汉明距离

进入正题

判断字符是否唯一

class Solution {
public:
    bool isUnique(string astr) {
        if (astr.size() > 26)
            return false;
        int bit = 0;
        for (auto e : astr) {
            if (bit >> (e - 'a'))
                return false;
            else
                bit |= 1 << (e - 'a');
        }
        return true;
    }
};

判断是否为子符重排
两整数之和

只出现一次的数字3
丢失的数字
消失的两个数字
该题为前两题解法相结合

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值