zoukankan      html  css  js  c++  java
  • 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.

    思路:

    To get a better preparation for interviews, I decided to explain my ideas in English. 

    Here is what I thought: 

    1) For any given m and n, as long as m != n, we always get 0 at right-most bit when we do AND operation on these numbers. It is because two adjacent numbers always have different right-most bit. There always be a 0!

       like:  5: 0101

        6: 0110

     result:   0100

    2) So, we keep doing right shift until m is equal to n. And we count the number of times of right shift(keep this number in "count").  

    3) We do left shift to m. Do it "count" times. 

     1     public int rangeBitwiseAnd(int m, int n) {
     2         if (m == 0) {
     3             return 0;
     4         }
     5         int count = 0;
     6         while (m != n) {
     7             m >>>= 1;
     8             n >>>= 1;
     9             count++;
    10         }
    11         return m <<= count;
    12     }
  • 相关阅读:
    hdu 1045 Fire Net
    hdu 1044 Collect More Jewels
    hdu 1043 Eight
    hdu 1042 N!
    hdu 1041 Computer Transformation
    hdu 1040 As Easy As A+B
    CI在ngnix的配置
    angularjs表单验证checkbox
    chrome浏览器跨域设置
    angularjs向后台传参,后台收不到数据
  • 原文地址:https://www.cnblogs.com/gonuts/p/4436574.html
Copyright © 2011-2022 走看看