LintCode Q179 Update Bits in Python

  • Jinhai ZHOU
  • 3 Minutes
  • 2017年1月5日
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution:
#@param n, m: Two integer
#@param i, j: Two bit positions
#return: An integer
def updateBits(self, n, m, i, j):
# write your code here
# max integer in python is 1 << 63 - 1, it's not 1 << 32
# so bit manipulation is not as perfermance as Java
bit_view = []
for k in xrange(32):
bit_view.append(n % 2)
n /= 2
for k in xrange(i, j + 1):
bit_view[k] = m % 2
m /= 2
ans = 0
# value
for k in xrange(31):
if bit_view[k] == 1:
ans |= (bit_view[k] << k)
# sign bit
if bit_view[31] == 1:
ans -= 1 << 31 # simulate 2's compliment
return ans
知识共享许可协议
本作品采用知识共享署名-相同方式共享 4.0 国际许可协议进行许可。