异或找唯一整数的程序是错的!

2021/11/30 20:38:59

本文主要是介绍异或找唯一整数的程序是错的!,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

// https://stackoverflow.com/questions/41181004/bitwise-xor-operator-to-find-missing-unique-id
public int findUniqueDeliveryId(int[] deliveryIds) {
        int uniqueDeliveryId = 0;
        for(int i = 0; i < deliveryIds.length; i++) {
            uniqueDeliveryId ^= deliveryIds[i];
        }
        return uniqueDeliveryId;
    }

上面的程序是错的!

def findUniqueDeliveryId(deliveryIds):
    uniqueDeliveryId = 0;
    for i in deliveryIds: uniqueDeliveryId ^= i; 
    # 我这里没错,我不用deliveryIds[i]
    for i in deliveryIds: print(i)
    return uniqueDeliveryId
def test(l): print(l, findUniqueDeliveryId(l))
test([0, 1, 1]) # 0
test([3, 5, 5, 5]) # 6
test([3, 2, 2]) # 3

^, xor, exclusive or. 0^0=0, 0^1=1, 0^x=x, 1^0=1, 1^1=0.

异或没有进位这一说,和加法不同。把0^1^0^0^0这样的一串一位二进制数(二进制位)搞明白了,12 ^ 23 ^ 167这样的十进制数也就搞明白了——它们都是一串二进制位。每位都对则整个数对。

任意多个0异或之后还是0.
0 = 0
0 ^ 0 = 0
0 ^ 0 ^ 0 = 0
0 ^ 0 ^ 0 ^ 0 = 0
0 ^ 0 ^ 0 ^ 0 ^ 0 = 0
任意多个1异或,结果与1的个数有关。
1 = 1
1 ^ 1 = 0
1 ^ 1 ^ 1 = 1
1 ^ 1 ^ 1 ^ 1 = 0
1 ^ 1 ^ 1 ^ 1 ^ 1 = 1

111x11或00x00000按位异或,可分别看成x11111或x0000000按位异或。

1 ^ 偶数个1 = 1 ^ 0 = 1; 1 ^ 偶数个0 = 1 ^ 0 = 1; 别的情况基本都对。
1 ^ 偶数个1符合题意。3=11, 5=101,最低位都是1。判断len是奇数偶数好像也没用。按题意,len>=3. 2个数谈不到unique.

def get_unique_num(ary) {
    if a[0] == a[1]:
        return a[2];
    else # a[0] != a[1]
        #return a[0] if a[1] == a[2] else a[1]
        if a[1] == a[2]:
            return a[0]; # 1, 2, 2
        else: # 2 1 2 
            return a[1]
}

我这个也是错的,比如输入是2, 2, 2, 1, 打个补丁吧:

if a[0] == a[1]:
  not_unique_num = a[0]
  while a[i] == not_unique_num: ...

用异或交换两个变量的值=奇技淫巧。嵌入式系统内存也没有那么紧张。The Raspberry Pi 2 Model B is the second-generation Raspberry Pi. It replaced the original Raspberry Pi 1 Model B+ in February 2015. It has:
1. A 900MHz quad-core ARM Cortex-A7 CPU
2. 1GB RAM
Like the (Pi 1) Model B+, it also has:
3. 100 Base Ethernet
4. 4 USB ports
5. 40 GPIO pins
6. Full HDMI port
7. Combined 3.5mm audio jack and composite video
8. Camera interface (CSI)
9. Display interface (DSI)
10. Micro SD card slot
11. VideoCore IV 3D graphics core
¥20.9

我不是反对学位运算。In Hacker's Delight, Second Edition, Hank Warren once again compiles an irresistible collection of programming hacks: timesaving techniques, algorithms, and tricks that help programmers build more elegant and efficient software, while also gaining deeper insights into their craft. Warren's hacks are eminently practical, but they’re also intrinsically interesting, and sometimes unexpected, much like the solution to a great puzzle. 音视频编解码处理位时用得上,尤其是找start code.



这篇关于异或找唯一整数的程序是错的!的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程