Bitwise AND of Numbers Range--LeetCode,leetcode

來源:互聯網
上載者:User

Bitwise AND of Numbers Range--LeetCode,leetcode

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.

思路:第一個思路肯定是從第一個數開始按位與,但是這樣的複雜度太高,開始有新的改進,如果這個範圍內有2的冪,那麼從這個開始按位或即可,這個2的冪要緊挨著n,如果發現這個2的冪次小於m,那麼仍然從這個範圍開始安裝或。

int rangeBitwiseAnd(int m, int n) {int i;int result ;for(i=0;;i++)if(pow(2,i)>n)break;if(pow(2,i-1) < m){result = m;for(i=m+1;i<=n;i++) result  &= i; }   else{result = pow(2,i-1);i = pow(2,i-1)+1;for(;i<=n;i++) result &= i;}     return result;} 

看別人的代碼,發現有更快的,對於一個連續的數字序列,兩個相鄰的兩個數最後一位肯定是不一樣的,那麼只要m!=n,那麼最後一位肯定是0,那麼我們就看從哪一位開始m==n即可。

int rangeBitwiseAnd(int m, int n) {          int offset = 0;          while (m && n)          {              if (m == n)              {                  return m << offset;              }              m >>= 1;              n >>= 1;              offset++;          }            return 0;      }  


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.