1 Star 0 Fork 0

徐长贺/Leetcode

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
_201.java 1.08 KB
一键复制 编辑 原始数据 按行查看 历史
Fisher Coder 提交于 7年前 . refactor 201 comment
package com.fishercoder.solutions;
/**
* 201. Bitwise AND of Numbers Range
*
* 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.
*/
public class _201 {
public static class Solution1 {
/**
* credit: https://discuss.leetcode.com/topic/28538/java-python-easy-solution-with-explanation
* Bitwise AND operation within range actually turns out to be doing some operations with just these two boundary numbers: m and n
* e.g. 5 and 7, in binary, they are 101 and 111, the result for [5,7] is 5&6&7 which is 101&110&111
* this we can understand it to be shifting the digits of m and n from left to right until they become the same, then we pad that number with zeroes on the right side
*/
public int rangeBitwiseAnd(int m, int n) {
int i = 0;
while (m != n) {
m >>= 1;
n >>= 1;
i++;
}
return (n << i);
}
}
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/isulong/Leetcode.git
git@gitee.com:isulong/Leetcode.git
isulong
Leetcode
Leetcode
master

搜索帮助