博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
LeetCode-Bitwise AND of Numbers Range
阅读量:4316 次
发布时间:2019-06-06

本文共 1460 字,大约阅读时间需要 4 分钟。

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.

Credits:

Special thanks to for adding this problem and creating all test cases.

 
 Analysis:
 
Find out the largest identical part starting from left of m and n, e.g.,
m = 20000, n=20218
1001110| 00100000
1001110| 10100000
Result:
1001110| 00000000
Solution:
public class Solution {    public int rangeBitwiseAnd(int m, int n) {        if (m>n || m==0) return 0;        if (m==n) return m;                int step =0;        while (m!=n){            m >>= 1;            n >>= 1;            step++;        }        return m<<=step;            }}

Solution 2:

If we do not know how to perform bit operator, we can still solve it like this:

public class Solution {    public int rangeBitwiseAnd(int m, int n) {        if (m>n || m==0) return 0;        if (m==n) return m;                StringBuilder mStr = new StringBuilder().append(Integer.toBinaryString(m));        StringBuilder base = new StringBuilder();        StringBuilder res = new StringBuilder();        for (int i=0;i
baseVal){ return Integer.parseInt(res.toString(),2); } else { res.setCharAt(i,'1'); } } } return Integer.parseInt(res.toString(),2); }}

 

转载于:https://www.cnblogs.com/lishiblog/p/5867054.html

你可能感兴趣的文章
正则表达式的搜索和替换
查看>>
个人项目:WC
查看>>
地鼠的困境SSL1333 最大匹配
查看>>
flume+elasticsearch+kibana遇到的坑
查看>>
【MM系列】在SAP里查看数据的方法
查看>>
C#——winform
查看>>
CSS3 transform制作的漂亮的滚动式导航
查看>>
《小强升职记——时间管理故事书》读书笔记
查看>>
Alpha 冲刺(3/10)
查看>>
Kaldi中的Chain模型
查看>>
spring中的ResourceBundleMessageSource使用和测试示例
查看>>
css规范 - bem
查看>>
UVALive 6145 Version Controlled IDE(可持久化treap、rope)
查看>>
mysql 将两个有主键的表合并到一起
查看>>
底部导航栏-----FragmentTabHost
查看>>
在linux中安装jdk以及tomcat并shell脚本关闭启动的进程
查看>>
apk,task,android:process与android:sharedUserId的区别
查看>>
前端实现文件的断点续传
查看>>
转:spring4.0之二:@Configuration的使用
查看>>
【Android开发】交互界面布局详解
查看>>