python C++ bit 計算O(1)時間解Leetcode 201 Bitwise AND of Numbers Range
----
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.
[codes on Leetcode]https://leetcode.com/problems/bitwise-and-of-numbers-range/solutions/4759874/bitwise-o32-time0ms-beats-100/
[Leetcode playList]https://www.youtube.com/watch?v=WjrWkPysfRM&list=PLYRlUBnWnd5IdDHk2BjqXwesydU17z_xk
[Dynamic Programming Playlist]https://www.youtube.com/watch?v=30yq3fmE6E8&list=PLYRlUBnWnd5K_XYUesV9oc6M9ONXII61T
#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))); } };
沒有留言:
張貼留言