1. no temporary variable swap two numbers
Exclusive-OR operation
- The same number of two exclusive OR is 0 i.e. n ^ n = 0;
- Any number of its own exclusive OR is 0, i.e. n ^ 0 = n.
- Support commutative, associative
a = a ^ b # (1)
b = a ^ b # (2)
a = a ^ b # (3)
Explained as follows:
The (1) a
into (2), there is
b = a ^ b = (a ^ b) ^ b = a ^ (b ^ b) = a ^ 0 = a
(1), (2) the same way result into (3), there is
a = a ^ b = (a ^ b) ^ a = (a ^ a) ^ b = 0 ^ b = b
2. determining a number of parity
AND operation
- 0 is the same, different 1
Analyzing a number n is even or odd, is determined only last a binary n is 1 or 0. It is 0 indicates an even number, an odd number is represented by 1.
if n & 1 == 1: # n为奇数
3. Take 2 / Division 2
n << 1 # 左移一位,表示乘2
n >> 1 # 右移一位,表示除2
4. The maximum value of the two numbers
def max(a, b):
return b & ((a-b) >> 31) | a & (~(a-b) >> 31)
Explained as follows:
b & ((a-b) >> 31)
Wherein(a-b) >> 31
represents taking(a-b)
the sign bit.
When b <= a
, the sign bit is 0,b & 0 = 0
When b > a
, the sign bit is -1.b & -1 = b
That is when b > a
when the result is b, 0 otherwise.
a & (~(a-b) >> 31)
Wherein the(~(a-b) >> 31)
representation of(a-b)
the symbol bit inversion .
When a >= b
, the result is inverted -1a & -1 = a
When a < b
, the negation result is 0,a & 0 = 0
That is when a >= b
when the result is a, otherwise the result is 0.
- Finally, the first two results of
或
calculation, since the result of the first two steps there must be a 0, a non-zero (i.e., maximum). Therefore, after或
the operation result is nonzero (i.e. maximum value).
The minimum value of the two numbers
def max(a, b):
return a & ((a-b) >> 31) | b & (~(a-b) >> 31)
6. The absolute value
def abs(n):
return (n ^ (n >> 31) - (n >> 31))
7. appears only to find out once digital
In a set of integer data, there is only one number appears once, the remaining digits appear twice. Find out which numbers appear only once.
Seen from the characteristics of the exclusive OR operation: two identical numbers XOR result is 0; and a number of exclusive OR result is 0 itself; XOR support and commutative and associative . So only XOR operation of all of the numbers, the result is only one number appears. Such asl = [1,2,1,0,0]
1 ^ 2 ^ 1 ^ 0 ^ 0 = (1 ^ 1) ^ (0 ^ 0) ^ 2 = 0 ^ 0 ^ 2 = 2
def find_only(l):
tmp = l[0]
for i in range(1, len(l)-1):
tmp ^= l[i]
return tmp
l = [1,2,3,4,4,3,1,0,0]