Python solution


  • 1
    H
     class Solution:
        # @param {integer} m
        # @param {integer} n
        # @return {integer}
        def rangeBitwiseAnd(self, m, n):
            x=0
            while n-m>=2:
                x+=1
                n>>=1
                m>>=1
            return (m & n)<<x

  • -1
    P
    class Solution {
    public:
      int rangeBitwiseAnd(int p, int q) {
           unsigned int Output=0;
           unsigned int m=p,n=q;
           if(m==n)
           {
               return m;
           }
           else if(m<1)
           {
               return 0;
           }
           	   	  unsigned int x=m&1073741824,y=n&1073741824;
                  while(x==y)
                  {
                          Output=(Output<<1)+(x>>30);
                          m=m<<1;
                          n=n<<1;
                          x=m&1073741824;
                          y=n&1073741824;
                  }
           if(Output>0)
           {
        	while(Output<q)
        	{
        		Output=Output<<1;
        	}
        	return Output/2;
           }
           return Output;
       }
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.