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; }}
- 疯狂Java之学习笔记(21)-------------final && static
- uva 11258 String Partition (DP)
- [LeetCode]-004-Median of Two Sorted Arrays
- DOM事件处理程序总结
- 如何在EA(Enterprise Architect)中自定义数据类型(Data Type)---转
- LeetCode 201-Bitwise AND of Numbers Range
- [C/C++]_[初级]_[标准库之几种算法库函数的运用,如字符串查找(字符个数查找)、分隔、删除、替换、排序、字符交换位置、大小写转换等等]
- open vswitch代码目录介绍
- java常见类
- activity task
- Android Handler机制
- 【数学】Count Primes
- Eclipse导入开源库,src文件夹下为空的解决方法
- JSON详解