leetcode_201题——Bitwise AND of Numbers Range(位操作)

Bitwise AND of Numbers Range

  Total Accepted: 9698 Total Submissions: 35771My Submissions

 

Given a range [m, n] where 0 <= m <= n <= 2147483647, return the bitwise AND of all numbers in this range, inclusive.

For example, given the range [5, 7], you should return 4.

Credits:
Special thanks to @amrsaqr for adding this problem and creating all test cases.

 

Hide Tags
  Bit Manipulation
Have you met this question in a real interview? 
Yes
 
No
 

Discuss

 

这道题开始最简单想到的是从m到n一个个位与,超时了

接着想到每一位,从m到n依次看是否为0还是1,发现还是超时了

最后比较快的想法是,int有32位,除去最高位的符号位,从最高位算起,只要有m和n中有不相同的,低位就不用算了,肯定不相同

#include<iostream>

using namespace std;



/*

int rangeBitwiseAnd(int m, int n) {

	int a=m;

	for(int i=m;i<=n;i++)

		a=a&i;

	return a;

}*/



/*

int rangeBitwiseAnd(int m, int n) 

{

	int last=0;

	for(int i=0;i<31;i++)

	{

		int flag=0;

		for(int j=m;j<=n;j++)

			if((j&(1<<i))==0)

			{

				flag=1;

				break;

			}

		if(flag==0)

			last+=(1<<i);

	}

	return last;

}

*/



int rangeBitwiseAnd(int m, int n) 

{

	int last=0;

	for(int i=30;i>=0;i--)//注意这里从30开始,因为最高位为符号位

	{

		if((m&(1<<i))==(n&(1<<i)))//若是这一位数相同

		{

			if((m&(1<<i))!=0)//不为0

				last+=(1<<i);

		}

		else

			break;

	}

	return last;

}



int main()

{

	//cout<<(1<<30)<<endl;

	//cout<<(1<<2)<<endl;

	//cout<<((1<<31)-1)<<endl;

	cout<<rangeBitwiseAnd(1,9)<<endl;

}

  

 

你可能感兴趣的:(LeetCode)