LeetCode 201-Bitwise AND of Numbers Range

来源:互联网 发布:eva625软件下载 编辑:程序博客网 时间:2024/06/11 23:48

Given a range [m, n] where 0 <= m <= n <= 2147483647, return Bitwise AND of Numbers Range 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.
题目解析:该题就是要求这范围内的数的共同的位
突然要做一个跟二进制有关的不能暴力的算法题,最好的方法就是先尝试几组数据。我们先从4bit的数字着手
0000 
0001
0010.
0011
0100
0101
0110
0111
1000
1001
1010
1011
1100
1101
1110
1111


有一个很明显很明显的规律。就是n & (n-1)的话永远会把n的最后一个1给消除掉。
如果我们从n一路&到m,n中的1总是从最低位开始被消成0的。
给一个很简单的例子 m= 64, n = 97
01100001 = 97
01100010 = 96
97&96 这一步消除了最后一个1,变成了01100000
01011111 = 95
(97&96)&95这一步消除了倒数第二个1,变成了01000000
此后就是一个很漫长的过程,因为从94 = 01011110开始和01000000进行&操作就不起作用了。
能对01000000起作用的就是00111111=63
所以这一题答案就是01000000 = 64


这一题为什么不能用loop来做?因为loop的过程中我们要做太多无用功,而真正干活的就是消除最低位1的那几步。
谈到“消除最低位1”的时候我们就该知道,这个题目其实和上文提及到的 “count 1s in a number”经典问题其实是一样,只不过
上文的那一题的while条件是大于0,而这一题则是大于m

代码:

public class Solution {    public int rangeBitwiseAnd(int m, int n) {        int p = 0;          while (n>m)          {             n=n&(n-1);        }                    return n;  }}

0 0
原创粉丝点击