Bitwise_AND_of_Numbers_Range
来源:互联网 发布:宁夏国培网络研修 编辑:程序博客网 时间:2024/06/06 16:45
题目描述:
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二进制编码中,相同的前缀 .)
思路:将两个数同时向右移位直到,两个数相同那么此时便是两个数的相同前缀,将相同的前缀恢复到原来的位置即可。
例如5(0101)和7(0111),向右移动位数,在移动两位之后两个数的二进制均变成了(0001),最后再左移相同位数(0100)就是最后结果。
public class Bitwise_AND_of_Numbers_Range {public static int rangeBitwiseAnd(int m, int n) { int count = 0; while(m!=n) { m >>= 1; n >>= 1; count++; } return m << count; }public static void main(String[] args) {int m = 5;int n = 7;System.out.println(rangeBitwiseAnd(m,n));}}
其中的位运算操作可以参考程序中位运算的妙用。
阅读全文
1 0
- Bitwise_AND_of_Numbers_Range
- HDU 6208 The Dominator of Strings 后缀自动机
- 成熟的产品环境代码:bounded capacity(受限容量)
- html元素的title属性
- 痤疮致增生性疤痕治疗心得
- oracle恢复删除的数据
- Bitwise_AND_of_Numbers_Range
- 07-javascript map&set
- ios-OC封装AFN中的GET和POST方法
- tensorflow之feed用法
- js正则表达式(一)
- jquery刷新页面
- Android开发实践:使用Service还是Thread
- android.view.WindowManager$BadTokenException
- 工厂模式