How python bitwise operator '~' working in this code?

42 Views Asked by At

Below code works fine and pass all the test cases but I don't know how this bitwise operator doing in this code, it's 275 leetcode problem:

class Solution:
    def hIndex(self, citations: List[int]) -> int:

        l, r = 0, len(citations)

        while(l<r):
            m = (l+r)//2
            if citations[~m] > m:
                l = m + 1
            else:
                r = m
        return l 
1

There are 1 best solutions below

0
SimonT On

The bitwise operator of ~m means it gives the complement of m. This is the number you get if you switch all the 1s to 0s and 0s to 1s so inverting the bits.

This gives you a NOT clause.