2015年10月24日星期六

Leetcode 201 Bitwise AND of Numbers Range

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.
Solution 1: from m to n, the leading common part of binary format will be kept, different part will be all zeros.
 public class Solution {  
   public int rangeBitwiseAnd(int m, int n) {  
     for (int i=0; i<32; i++) {  
       if (m==n) return m<<i;  
       m>>=1;  
       n>>=1;  
     }  
     return 0;  
   }  
 }  

没有评论:

发表评论