码迷,mamicode.com
首页 > 其他好文 > 详细

Bitwise AND of Numbers Range

时间:2015-04-16 13:57:59      阅读:104      评论: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.

 1 public class Solution {
 2     public int rangeBitwiseAnd(int m, int n) {
 3         if(m == 0)
 4             return 0;
 5         int result = 0;
 6         int temp = m;
 7         int bits[] = new int[32];
 8         for(int i = 0; i < 32; i++){
 9             bits[i] = (temp & 1);
10             temp >>>= 1;
11         }
12         
13         int carry = (n - m);
14         for(int i = 0; i < 32; i++){
15             carry = (carry + bits[i]) / 2;
16             if(bits[i] + carry > 1)
17                 bits[i] = 0;
18         }
19         
20         for(int i = 31; i >=0; i--){
21             result <<= 1;
22             result += bits[i];
23         }//for
24         
25         return result;
26     }
27 }

 

Bitwise AND of Numbers Range

标签:

原文地址:http://www.cnblogs.com/luckygxf/p/4431739.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!