首页 > 其他 > 详细

201.Bitwise AND of Numbers Range

时间:2015-12-11 18:23:25      阅读:117      评论:0      收藏:0      [点我收藏+]

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 @amrsaqr for adding this problem and creating all test cases.

思路:我们先以[26,30]为例,有:

11010 11011 11100 11101 11110

可见最后求得的结果是范围内所有的数公共的二进制前缀,即最终求得是最长公共二进制前缀。我们可以每次将m和n右移一位,直至m,n相等,同时记录向右移动的次数i,此时m就是我们要求的公共二进制前缀右移i位得到的数,将m左移i位即可求得最终结果。

  1. class Solution {
  2. public:
  3. int rangeBitwiseAnd(int m, int n) {
  4. int offset=0;
  5. while(m!=n){
  6. m>>=1;
  7. n>>=1;
  8. offset++;
  9. }
  10. return m<<offset;
  11. }
  12. };





201.Bitwise AND of Numbers Range

原文:http://www.cnblogs.com/zhoudayang/p/5039530.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!