Bitwise Ops
2018-03-09
Basic Knowledge
Twos-complement binary: 补码二进制, 计算机以补码的形式存储数字。
Bitwise operators in python:
XOR quality:
Problems
XOR’s quality
#156 Given an array of integers, every element appears twice except for one. Find that single one.
12345def singleNumber(nums):ret = 0for x in nums:ret ^= xreturn ret#168 Given an array containing n distinct numbers taken from 0, 1, 2, …, n, find the one that is missing from the array.
123456def missingNumber(self, nums):ret, n = 0, len(nums)for i in range(n):ret = ret ^ i ^ nums[i]ret = ret ^ nreturn ret#389 Given two strings s and t which consist of only lowercase letters.
String t is generated by random shuffling string s and then add one more letter at a random position.
Find the letter that was added in t.123456def findTheDifference(self, s, t):ret, ls = 0, len(s)for i in range(ls):ret ^= ord(s[i]) ^ ord(t[i])ret ^= ord(t[ls])return chr(ret)
XOR and Truth Table
List the truth table first and then change it into boolean algebra.
#137 Given an array of integers, every element appears three times except for one, which appears exactly once. Find that single one.
1234567def singleNumber(self, nums):bit1, bit2 = 0, 0for x in nums:last_bit1 = bit1bit1 = (~bit1 & bit2 & x) | (bit1 & ~bit2 & ~x)bit2 = ~last_bit1 & (bit2 ^ x)return bit2#variant Given an array of integers, every element appears once except for one, which appears exactly three times. Find that single one.
1234567def single_number(nums):bit1, bit2 = 0, 0for x in nums:last_bit1 = bit1bit1 = ~bit2 & (last_bit1 ^ x)bit2 = (~bit1 & bit2 & ~x) | (bit1 & ~bit2 & x)return bit1
XOR and Divide Groups
- #260 Given an array of numbers nums, in which exactly two elements appear only once and all the other elements appear exactly twice. Find the two elements that appear only once.1234567891011121314151617def singleNumber(self, nums):rst = 0for x in nums:rst ^= xmask = 1while not (mask & rst):mask <<= 1# divide into 2 groups by set bitrst1, rst2 = 0, 0for x in nums:if x & mask:rst1 ^= xelse:rst2 ^= xreturn [rst1, rst2]