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

// 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=011, 5=101,最低位都是1。6和7相同的位更多。和最低位(奇偶数)没关系。判断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: ...

这个好像是对的。2, 2 .... 1,不管1有多远,反正2出现了至少两次,所以不是唯一的。un-unique, un-unravel :-)

用异或交换两个变量的值=奇技淫巧。嵌入式系统内存也没有那么紧张。STM32F103RBT6,主频 72MHz,128KB FLASH ,20KB RAM。1978年的Appe I是4KB RAM。[修改: 8051的基础内存为128字节]

我不是反对学位运算。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.

posted @ 2021-11-30 19:24  Fun_with_Words  阅读(141)  评论(0编辑  收藏  举报









 张牌。