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.
鏈接:?http://leetcode.com/problemset/algorithms/
題解:
一開始采用暴力解,自然超時(shí)了。后來(lái)想了想,其實(shí)每次比較一個(gè)位置就可以了變成0以后不可能再變回1,所以能不能轉(zhuǎn)換為一個(gè)O(32)的運(yùn)算。因?yàn)閺膍到n的話其實(shí)就等于m + 1 + 1 + 1... ?~ n,假設(shè)從101000變換到110000,低5位總會(huì)被全部清0, 這樣我們只用從最高位往最低位置比較m和n的相同部分就可以了,或者從最低位向最高位比較,假如m和n個(gè)位不相等,則向右shift,繼續(xù)比較十位,以此類推。然而想到這里并沒(méi)有什么用,還沒(méi)寫code我就去看了discuss...于是得到了答案....要改掉這個(gè)壞毛病。
Time Complexity - O(1), Space Complexity - O(1)
public class Solution {public int rangeBitwiseAnd(int m, int n) {int count = 0;while(m != n) {m >> 1;n >> 1;count++;}return m << count;} }?
還有另外一種更簡(jiǎn)練的寫法在reference里。就是對(duì)n進(jìn)行末位清0,然后于m進(jìn)行比較,直到n <= m,然后返回n。
Time Complexity - O(1),Space Complexity - O(1)。
public class Solution {public int rangeBitwiseAnd(int m, int n) {while(m < n) n = n & (n - 1);return n;} }?
二刷:
用了上面的辦法。就是把n從最低起清零,然后跟m進(jìn)行比較,當(dāng)m >= n的時(shí)候,這時(shí)候我們找到了一個(gè)可能的解,返回n。
我們也可以從高位向低位比較。
Java:
Time Complexity - O(1), Space Complexity - O(1)
public class Solution {public int rangeBitwiseAnd(int m, int n) {while (m < n) n &= (n - 1);return n;} }?
三刷:
利用末位清零。
Java:
public class Solution {public int rangeBitwiseAnd(int m, int n) {while (m < n) {n &= (n - 1);}return n;} }?
?
?
Reference:
http://www.meetqun.com/thread-8769-1-1.html
https://leetcode.com/discuss/32115/bit-operation-solution-java
https://leetcode.com/discuss/32278/8line-c-simple-clear-solution
https://leetcode.com/discuss/32053/accepted-c-solution-with-simple-explanation
https://leetcode.com/discuss/35057/share-my-simple-java-solution
https://leetcode.com/discuss/34918/one-line-c-solution
https://leetcode.com/discuss/53646/simple-and-easy-to-understand-java-solution
?
轉(zhuǎn)載于:https://www.cnblogs.com/yrbbest/p/4493541.html
總結(jié)
以上是生活随笔為你收集整理的201. Bitwise AND of Numbers Range的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: cordova 5.0版本说明
- 下一篇: 从简单的信道预计说起