Exemple #1
0
 def main_bitwise(self, n):
     # get the leftmost bit
     if n == BitAlgorithm.getRightmostSetBit(n):
         m = n
     else:
         m = NumberAlgorithm.getNextPowerOfTwo(n) >> 1
         assert (m < n)
     # get rest bits except the leftmost one
     n &= m - 1
     return n << 1 | 1
Exemple #2
0
 def main_bitwise(self, n):
     # get the leftmost bit
     if n == BitAlgorithm.getRightmostSetBit(n):
         m = n
     else:
         m = NumberAlgorithm.getNextPowerOfTwo(n) >> 1
         assert (m < n)
     # get rest bits except the leftmost one
     n &= m - 1
     return n << 1 | 1
Exemple #3
0
    def _build(self, lst):
        def recur(sgt, low, high):
            if high - low < 1:
                return None
            assert (sgt < len(self.root))
            if high - low == 1:
                self.root[sgt] = self.__class__.Node(Interval(low, high), lst[low])
            else:
                mid = high - (high - low) / 2
                self.root[sgt] = self.__class__.Node(Interval(low, high),
                                                     self.up(recur(sgt << 1 | 1, low, mid),
                                                             recur((sgt + 1) << 1, mid, high)))
            return self.root[sgt].value

        assert (not self.root)
        self.root = [None] * ((NumberAlgorithm.getNextPowerOfTwo(len(lst)) << 1) - 1)
        assert (len(self.root) == len(lst) == 1 or len(self.root) > len(lst))
        recur(0, 0, len(lst))