首页 > 学院 > 开发设计 > 正文

201. Bitwise AND of Numbers Range

2019-11-08 19:49:25
字体:
来源:转载
供稿:网友

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.

解题思路:基数和偶数的and结果末位为0。为了找m,n之间的公共前缀,mn分别右移,并记录次数。

public class Solution { public int rangeBitwiseAnd(int m, int n) { if (m == 0) return 0; int factor = 1; while (m != n) { m >>= 1; n >>= 1; factor <<= 1; } return m*factor; }}public class Solution { public int rangeBitwiseAnd(int m, int n) { if (m == 0) return 0; int step = 0; while (m != n) { m >>= 1; n >>= 1; step++; } return (m<<step); }}public class Solution { public int rangeBitwiseAnd(int m, int n) { if (m == 0) return 0; int step = 0; while (m < n) { n &= (n-1); } return n; }}
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表