标签:-o while return man 第一个 set div xpl ref
题目:
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.
链接: http://leetcode.com/problemset/algorithms/
6/26/2017
不想做bit manipulation的题
我的思路是,先找最高位的1,如果不一样就直接返回0.如果一样的话就找之后第一个0,找到之后返回最高1和0之间的数。但是好难写,还不知道对不对
以下是抄别人的答案
1. 除掉末尾m, n不相同的元素,方法是先右移再左移
1 public class Solution { 2 public int rangeBitwiseAnd(int m, int n) { 3 int count = 0; 4 5 while(m != n) { 6 m >>= 1; 7 n >>= 1; 8 count++; 9 } 10 11 return m << count; 12 } 13 }
2. 输入条件中, m <= n。通过运算,当m >= n时,看当时n的高位的情况,此时n含有共同的高位1。n = n * (n - 1)是为了清最右边的一个1
1 public class Solution { 2 public int rangeBitwiseAnd(int m, int n) { 3 while(m < n) 4 n = n & (n - 1); 5 6 return n; 7 } 8 }
参考
http://www.cnblogs.com/yrbbest/p/4493541.html
别人的解法
https://discuss.leetcode.com/topic/12133/bit-operation-solution-java
这个不是很懂
https://discuss.leetcode.com/topic/13508/one-line-c-solution
有解释
https://discuss.leetcode.com/topic/20176/2-line-solution-with-detailed-explanation
更多讨论
https://discuss.leetcode.com/category/209/bitwise-and-of-numbers-range
201. Bitwise AND of Numbers Range
标签:-o while return man 第一个 set div xpl ref
原文地址:http://www.cnblogs.com/panini/p/7082289.html