当前位置:网站首页>异或的应用。(提取出数字中最右侧的1,面试中经常用的到)
异或的应用。(提取出数字中最右侧的1,面试中经常用的到)
2022-06-28 07:29:00 【Kinght_123】

我们都知道,在计算机系统中,所有数字的存储方式都是二进制,那么我们需要提取数字中的最右侧的1该怎么办呢?
一、背景
异或的应用十分的重要。比如当我们面试时,面试官问了一个问题:在一堆数字中,只有两个数字出现的次数为奇数次,其他的数字出现的次数都为偶数次,要求求出奇数次的数字a和b,要求时间复杂度O(N),额外空间复杂度O(1).
二、解题思路
首先,我们需要异或一遍数组,这样得到的结果就是a^b,然后怎么算呢?
然后a^b肯定是不为0的,我们需要知道a或者b的数值就可以算出结果,那么怎么知道a或者b呢?
a和b在计算机的存储形式中都是以二进制的方式存储的,又因为a一定不等于b,所以我们知道a和b中的某一位绝对是不相同的。利用这个特点,假设我们找到最右侧的不相同的位(也就是a的那一位数字为0,而b的那一位数字为1,或者相反),那我们怎么找到最右侧的1呢?
right_one = arr & (~arr + 1) # 提取最右侧的1
这行代码就很好的找到了最右侧的1,下面我来解释一下,首先arr的数值是a^b的结果,那么我们给这个结果取反,然后加1,此时的arr的最右侧的1就是答案。
比如arr的结果是000111001100.取反之后为111000110011,加上1之后为111000110100,那么此时的最右侧的1就是最终答案。
找到之后,我们可以利用这个来再次遍历数组,此时的结果就是a或者b,然后让这个结果异或arr,这样就得到了两个数字。
三、完整的代码
nums = [10, 10, 10, 5, 6, 6, 7, 7, 8, 8, 9, 9, 55, 55, 66, 66, 33, 33, 5, 888, 888, 888]
arr = 0
for i in range(len(nums)):
arr ^= nums[i] # 此时的arr为a^b
right_one = arr & (~arr + 1) # 提取最右侧的1
eor = 0
for i in range(len(nums)):
if nums[i] & right_one == 0:
eor ^= nums[i]
print(f'两个数字为{
eor}和{
arr^eor}')
输出:
两个数字为888和10
边栏推荐
- Leetcode+ 66 - 70 high precision, two sub topics
- Modifying MySQL port number under Linux
- ice, protobuf ,thrift -- 笔记
- Jetpack - defects of livedata component and Countermeasures
- LLVM 与 Clang
- R language hitters data analysis
- Real time database - Notes
- kubelet垃圾(退出的容器和未使用的镜像)回收源码分析
- golang gin框架进行分块传输
- Vivo browser rapid development platform practice - Overview
猜你喜欢

Evolution of vivo push platform architecture

Comment la passerelle BACnet / IP recueille - t - elle les données du système central de contrôle des bâtiments?

Using interceptor and cache to complete interface anti brushing operation
![[ thanos源码分析系列 ]thanos query组件源码简析](/img/e4/2a87ef0d5cee0cc1c1e1b91b6fd4af.png)
[ thanos源码分析系列 ]thanos query组件源码简析

open62541直接导入NodeSet文件

小小一款代码编辑器竟然也可以有程序运行之功能——Sublime Text3运行各种语言程序的总结

Leetcode+ 51 - 55 retrospective and dynamic planning topics

Modifying MySQL port number under Linux

hack the box:RouterSpace题解

BACnet/IP網關如何采集樓宇集中控制系統數據
随机推荐
Is it safe for flush to open an account online
Compilation principles final review
MySQL installation steps - Linux configuration file JDK installation (II)
vite2.9 中指定路径别名
[thanos source code analysis series]thanos query component source code analysis
Ice - resources
ABAP 技能树
MMR重排(相似度通过编辑距离和重复度计算)
Introduction and several months' experience of extending the solution thanos of Prometheus
The practice of traffic and data isolation in vivo Reviews
Force buckle 515 Find the maximum value in each tree row
Will Internet talents be scarce in the future? Which technology directions are popular?
7-1 懂的都懂
Dbeaver 22.1.1 release, visual database management platform
Recommend several 0 code, free, learning and using visualization tools
R 语言 ggmap 可视化集群
卸载重装最新版mysql数据库亲测有效
flutter 实现摇一摇功能
华为云计算之物理节点CNA安装教程
Practice of traffic recording and playback in vivo