leetcode No201. Bitwise AND of Numbers Range
来源:互联网 发布:知否什么时候上映 湖南 编辑:程序博客网 时间:2024/06/06 19:56
Question:
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.
即把在 m <= n 这个范围内的所有元素相与
Algorithm:Bit Manipulation
我们不妨先举几个例子:
1、m=5(1001),n=5(1001);m-n=0 return 5(1001)
2、m=6(0110),n=7(0111);m-n=1 reurn 6(0110)
3、m=6(0111),n=8(0100);m-n=2 return 4(0100)
4、m=8(1000),n=15(1111);m-n=7 return 8(1000)
我们可以发现,m-n的最高位决定了result的最低位(这句话不知道怎么说。。。)所以我们只需m&n再把低位置0(置零的位数由m-n决定)
举个例子result为32位的二进制,假设m-n的最高位为2,则result的后两位为0,所以result = m&n&(0xfffffffc)
Submitted Code:
class Solution {public: int rangeBitwiseAnd(int m, int n) { long long int range = n-m; long long int rangebit=0xffffffff; while(range) //使range的二进制位数全变0,高位仍为1 { rangebit = rangebit << 1; range /= 2; } return m&n&rangebit; }};
Accepted Solutions Runtime Distribution:
0 0
- 进制溢出
- POj 1580(字符串处理)
- python 抓取网页数据
- Lua语法学习(一)
- 关于python csv文件打开错误:_csv.Error: line contains NULL byte
- leetcode No201. Bitwise AND of Numbers Range
- Hibenate-注解
- 趣学 C 语言(十三)—— 标准输入输出重定向
- Java 读取properties配置文件
- C++的标准命名空间使用
- ORACLE 11G ASM DISKGROUP COMPATIBILITY
- 异常和随机整数的结合题
- java09--线程
- iOS开发中UITableView和UITableViewCell的几种样式