leetcode 201. Bitwise AND of Numbers Range 最长公共前缀问题 + 位操作

Dear 丶 2022-06-08 09:12 258阅读 0赞

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.

这道题最自觉的做法就是循环做位and操作,但是我在网上看到了一个做法, 想法很棒,这道题可以直接转化为另一个问题:再一串连续的数组中,寻找他们的公共前缀。

直接暴力去计算可能要超时

代码如下:

  1. /*
  2. * 这道题考察的是位运算的使用
  3. * 那么这道题其实并不难,我们先从题目中给的例子来分析,
  4. * [5, 7]里共有三个数字,分别写出它们的二进制为:
  5. * 101  110  111
  6. * 相与后的结果为100,仔细观察我们可以得出,最后的数是该数字范围内所有的数的左边共同的部分,
  7. * 如果上面那个例子不太明显,我们再来看一个范围[26, 30],它们的二进制如下:
  8. * 11010  11011  11100  11101  11110
  9. *
  10. * 那么本题就可以转化为另一个问题,直接找一串连续数字的公共前缀
  11. *
  12. * */
  13. public class Solution
  14. {
  15. public int rangeBitwiseAnd(int m, int n)
  16. {
  17. int i=0;
  18. while(m!=n)
  19. {
  20. m=m>>1;
  21. n=n>>1;
  22. i++;
  23. }
  24. return (m<<i);
  25. }
  26. /*
  27. * 这是直接做或操作,但是可能超时
  28. * */
  29. public int rangeBitwiseAndByLoop(int m, int n)
  30. {
  31. int res=m;
  32. for(int i=m+1;i<=n;i++)
  33. res &=i;
  34. return res;
  35. }
  36. }

下面是C++的做法,这道题肯定是用位运算来组,最直接的做法就是循环遍历去做,但是会超时,后来网上发现了一个寻找公共前缀的做法,很棒

代码如下:

  1. #include <iostream>
  2. #include <vector>
  3. #include <string>
  4. #include <map>
  5. #include <cmath>
  6. #include <queue>
  7. #include <stack>
  8. #include <algorithm>
  9. using namespace std;
  10. class Solution
  11. {
  12. public:
  13. int rangeBitwiseAnd(int m, int n)
  14. {
  15. int i = 0;
  16. while (m != n)
  17. {
  18. m = m >> 1;
  19. n = n >> 1;
  20. i++;
  21. }
  22. return m << i;
  23. }
  24. };

发表评论

表情:
评论列表 (有 0 条评论,258人围观)

还没有评论,来说两句吧...

相关阅读