C++ easy understanding using bit manipulation


  • 0
    J

    The only tricky point about my code is the idx. That integer value is used to record an index which shows that n and m has the same bit from the highest bit to the idx bit.

    For example: m=10, n=11, after the while loop, the idx would be 1. Since 10=1010, 11=1011, the idx shows that 10 and 11 both begin with '101'.

        int rangeBitwiseAnd(int m, int n) {
        	int i=0,j=0,idx=0,x=n;
        	while(m>0 && n>0){
        		i++;
        		j++;
                    if((n&1)!=(m&1)) idx=i;
        		n = n>>1;
        		m = m>>1;
        	}
        	if(n!=0)  return 0;
        	return (x>>idx)<<idx;
        }
    

Log in to reply
 

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