Leetcode: Bitwise AND of Numbers Range
2015-08-05 23:49
387 查看
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.
有些难度,一定不是O(n)的方法。如果M不等于N,那么最后一位一定有0和1,可以清0,移位一直判断这个。
class Solution {
public:
int rangeBitwiseAnd(int m, int n) {
int shift = 0;
while (m != n) {
m >>= 1;
n >>= 1;
++shift;
}
return m << shift;
}
};
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.
有些难度,一定不是O(n)的方法。如果M不等于N,那么最后一位一定有0和1,可以清0,移位一直判断这个。
class Solution {
public:
int rangeBitwiseAnd(int m, int n) {
int shift = 0;
while (m != n) {
m >>= 1;
n >>= 1;
++shift;
}
return m << shift;
}
};
相关文章推荐
- 使用位运算实现网页中的过滤、筛选功能实例
- C#枚举中的位运算权限分配浅谈
- shell 基本计算、逻辑运算、位运算详解
- Java位运算和逻辑运算的区别实例
- 优秀程序员必须知道的20个位运算技巧
- JavaScript使用位运算符判断奇数和偶数的方法
- java位运算加密示例
- c语言中用位运算实现加法技巧介绍
- leetcode 179 Largest Number
- leetcode 24 Swap Nodes in Pairs
- leetcode 2 Add Two Numbers 方法1
- leetcode 2 Add Two Numbers 方法2
- Java 位运算(移位、位与、或、异或、非)
- 位运算应用口诀和实例
- [LeetCode]47 Permutations II
- [LeetCode]65 Valid Number
- [LeetCode]123 Best Time to Buy and Sell Stock III
- [LeetCode] String Reorder Distance Apart
- [LeetCode] Sliding Window Maximum
- [LeetCode] Find the k-th Smallest Element in the Union of Two Sorted Arrays