示例#1
0
 def getPrevSmallerNumber(self, num):
     #first find the non trailing 1
     oneCounter = 0
     pivot = -1
     bitCounter = -1
     foundZero = False
     curNum = num
     while curNum > 0:
         bitCounter += 1
         if curNum % 2 == 0:
             foundZero = True
         else:
             if foundZero:
                 pivot = bitCounter
                 break
             else:
                 oneCounter += 1
         curNum = curNum // 2
     if pivot == -1:
         return None
     #now we need to:
     #reset the bit at pivot till start, add back oneCounter+1 "1"
     temp = Generic.clearBitFromStart(num, pivot)
     print(Generic.DecToBinaryString(temp))
     setNum = (1 << oneCounter + 1) - 1
     print(Generic.DecToBinaryString(setNum))
     temp = temp | setNum
     print(Generic.DecToBinaryString(temp))
     return temp
示例#2
0
 def insertion(self, a, b, i, j):
     if len(b) > j - i + 1:
         raise IndexError
     #Create mask of 0 from j -> i, rest should be 1 -> ~ (1 from i-j)
     numA = Generic.BinaryStringToDec(a)
     numB = Generic.BinaryStringToDec(b)
     #Clear bit j->i of num A
     mask = ~(Generic.clearBitFromStart(((1 << j + 1) - 1), i - 1))
     numA = numA & mask
     #shit left num b i bit
     numB = numB << i
     return Generic.DecToBinaryString(numA | numB)
import BitManipulation.Generic as Generic


class Solution:
    def pairwiseSwap(self, num):
        #Assume number is of type integer 32 bits
        onlyEven = 0xAAAAAAAA
        onlyOdd = 0x55555555
        #calculate even and odd bit number
        even = num & onlyEven
        odd = num & onlyOdd
        #shift right even + shiftleft odd
        even = even >> 1
        odd = odd << 1
        return even | odd


if __name__ == '__main__':
    bin = "110110101101100"
    print(" " + bin)
    num = Generic.BinaryStringToDec(bin)
    A = Solution()
    res = A.pairwiseSwap(num)
    print(Generic.DecToBinaryString(res))
示例#4
0
#Find number of bit needed to be flipped to turn a -> b
import BitManipulation.Generic as Generic

class Solution:
    def conversion(self,a ,b):
        res = 0
        while a > 0 and b > 0:
            if a%2 != b%2:
                res += 1
            a = a//2
            b = b//2
        while a>0:
            if a%2 == 1:
                res += 1
            a = a//2
        while b > 0:
            if b%2 == 1:
                res += 1
            b = b//2
        return  res

if __name__ == '__main__':
    a = 100
    b = 15
    print(Generic.DecToBinaryString(a))
    print(Generic.DecToBinaryString(b))
    A = Solution()
    print(A.conversion(b,a))