LeetCode 6194. 最小 XOR

C++硬解,位运算的一个题目

class Solution {
public:
    int minimizeXor(int num1, int num2) {
        //把num1转换为2进制字符串,从低位到高位,统计1的个数
        string s1 = "";
        int c1 = 0;
        while(num1)
        {
            if(num1 % 2 == 1)
            {
                s1 += '1';
                c1++;
            }
            else
                s1 += '0';
            num1 /= 2;
        }

        //把num2转换为2进制字符串,从低位到高位,统计1的个数
        string s2 = "";
        int c2 = 0;
        while(num2)
        {
            if(num2 % 2 == 1)
            {
                s2 += '1';
                c2++;
            }
            else
                s2 += '0';
            num2 /= 2;
        }

        //结果的二进制字符串,这里要注意字符串s长度应为s1和s2中最大的长度
        string s = "";
        int size = s1.size();
        if(s2.size() > s1.size())
            size = s2.size();
        for(int i = 0; i < size; i++)
        {
            if(i < s1.size() && s1[i] == '1')
                s += '1';
            else
                s += '0';
        }

        //如果s1中1多
        if(c1 > c2)
        {
            int c = c1 - c2;
            for(int i = 0; i < s.size(); i++)
            {
                if(s[i] == '1')
                {
                    s[i] = '0';
                    c--;
                    if(c == 0)
                        break;
                }
            }
        }
        else if(c1 < c2) //如果s2中1多
        {
            int c = c2 - c1;
            for(int i = 0; i < s.size(); i++)
            {
                if(s[i] == '0')
                {
                    s[i] = '1';
                    c--;
                    if(c == 0)
                        break;
                }
            }
        }

        int res = 0;
        int p = 0;
        for(int i = 0; i < s.size(); i++)
        {
            if(i == 0)
                p = 1;
            else
                p *= 2;
            if(s[i] == '1')
                res += p;
        }
        return res;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值