Bit operation is difficult ... Especially when it comes to writing in programming ...
bit.py
#-*- coding:utf-8 -*-
class Bitutils():
def getNextArith(self,n):
c = n
c0 = 0
c1 = 0
while c & 1 == 0 and c != 0:
c0 += 1
c >>= 1
while c & 1 == 1:
c1 += 1
c >>= 1
if (c0 + c1 == 31 or c0 + c1 == 0):
return -1
return n + (1 << c0) + (1 << (c1 -1)) -1
def getPrevArith(self,n):
temp = n
c0 = 0
c1 = 0
while temp & 1 == 1:
c1 += 1
temp >>= 1
if temp == 0:
return -1
while temp & 1 == 0 and temp != 0:
c0 += 1
temp >>= 1
return n - (1 << c1) - (1<<(c0 - 1)) + 1
I will think again after taking a bath.