[LeetCode#201] Bitwise AND of Numbers Range
2015-09-02 23:17
288 查看
Problem:
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.
Analysis:
Solution:
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.
Analysis:
The idea behind this problem is not hard, you could easily think out the solution. But for the implementation, you may trap yourself into some sterotypes. Idea: Since for bitwise 'AND' operation, as long as there is a '0' appears, the digit should become 0. Principle in digit change in range: (work for numerial system, binary system and other system too) Start: 1011111100111010101010 End: 1011111110001010010101 To reach 10001010010101 from 00111010101010. We must start to add 00000000000001 onto 00111010101010 => 00111010101011 ... We can we reach the '1' in high index, all digits behind after it must change once. That's to say, all the digits after 1 (include 1) should become 0. answer: 1011111110000000000000 Algorithm: Step 1: Find the first left bit 'start' differ from 'end'. Start: 10111111[0]0111010101010 End: 10111111[1]0001010010101 Step 2: Make all bits after the first different bits (include first different bit) into 0. The number is the answer we wish to get. 10111111[0]0111010101010 => 10111111000000000000 Great implementation: Move bit to reach the answer!!!! See the solution!
Solution:
public class Solution { public int rangeBitwiseAnd(int m, int n) { if (m < 0 || n < 0) throw new IllegalArgumentException("the passed in arguements is not tin the valid range!"); int p = 0; while (m != n) { m = m >> 1; n = n >> 1; p++; } return m << p; } }
相关文章推荐
- 微信公众平台开发教程(五)自定义菜单
- Dijkstra算法研究(深度解析/C++实现)
- Python的Threading模块的Thread对象的join方法
- 项目实战No2 登陆注册
- 关于示波器地线的问题!
- PagerSlidingTabStrip源码分析及扩展
- odoo费用报销流程
- 微信公众平台开发教程(四) 实例入门:机器人(附源码)
- uva 707 - Robbery(记忆化搜索)
- 在一个list列表中的多个dict字典按照键值对key-value来进行排序
- hdu 2544 最短路(floyd)
- BZOJ 2429: [HAOI2006]聪明的猴子( MST )
- C++ Primer 读书笔记整理(一)
- 微信公众平台开发教程(三) 基础框架搭建
- 一些容易忽略的知识
- spring事务PROPAGATION_REQUIRES_NEW和PROPAGATION_NESTED区别
- 2015-阿里C++研发附加题第一题
- 微信公众平台开发教程(二) 基本原理及消息接口
- MFC利用正则表达式进行密码匹配
- Java设计模式--Java设计模式介绍