位运算习题全解

Leetcode:137. Single Number II 位运算解题

题目链接
重在真值表补充
在这里插入图片描述
在这里插入图片描述

leetcode上的没看明白直接上真值表的代码(学过)

class Solution:
    def singleNumber(self, nums: List[int]) -> int:
        ones, twos = 0, 0
        for num in nums:
            tt1 = ((~num)&(~twos)&ones | (num&~twos&~ones))//可以提~tows,然后和后面异或
            tt2 = (((~num)&(twos)&(~ones))|(num&~(twos)&ones))
            ones, twos = tt1, tt2
        return ones

C++解法 //leetcode点赞最多的第二种解法

#include<iostream>
using namespace std;
#include<vector>
#include<string>
#include<cstring>

int singleNumber(vector<int>& nums) 
{
	int ww[32];
	memset(ww,0, sizeof(ww));
	for(auto num:nums)
	{


		for(int i=0;i<32;i++)
		{
//			cout<<num;
			ww[i]+=(num&1);
//			cout<<ww[i]<<" ";
			num>>=1;
		}
//		cout<<endl;
	}
	int answer=0;
	for(int i=31;i>=0;i--)
	{
		answer|=ww[i]%3;
		if(i==0)
			break;
		answer<<=1;
	}
	return answer;

}

int main()
{
	vector<int> nums={3,3,1,3,1,1,2};

	cout<<singleNumber(nums); 
	return 0;
 } 

Leetcode:260. Single Number III

题目链接
题解:将整体数组分为两大类,每一类包含几对相同的数和一个只有一个的数字,每一类整体求异或即可

class Solution:
    def singleNumber(self, nums: List[int]) -> List[int]:
        nn = 0
        for num in nums:
            nn ^= num    //a^b,a,b为仅出现一次的数字
        single = nn &(-nn)   // 111011->000001 11110->00010 保留最后一位1
        arr1=0
        arr2=0
        for num in nums:
            if  num&single: //分为两类,因为a,b在single位肯定不同,其他每对都是相同的数字
                arr1^=num
            else:
                arr2^=num
        return [arr1, arr2]

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值