herrDeng網內搜尋

自訂搜尋

Ads

2024年2月21日 星期三

python C++ bit 計算O(1)時間解Leetcode 201 Bitwise AND of Numbers Range


python C++ bit 計算O(1)時間解Leetcode 201  Bitwise AND of Numbers Range
這就是用x&(x-1)技法。有人會說計算時間是O(log n),但32-bit整數,無論是迴圈或遞迴頂多32次。如果要熟透bit處理的訣竅,還有更厲害的技法,請進
----
python C++ bit calculation O(1) time solution Leetcode 201 Bitwise AND of Numbers Range
This is using the x&(x-1) technique. Some people would say that the calculation time is O(log n), but for 32-bit integers, no matter it is looping or recursing, it can be done at most 32 times.
#pragma GCC optimize("O3", "unroll-loops")
class Solution {
   public:
     int rangeBitwiseAnd(int left, int right) {
       if (left==0 ||countl_zero((unsigned)left)!=countl_zero((unsigned)right)) return 0;
       return left & right & -(1<<(32-countl_zero((unsigned)right-left)));
  }
};

沒有留言:

Related Posts Plugin for WordPress, Blogger...

熱門文章