【Leetcode】201. Bitwise AND of Numbers Range(区间二进制数或运算)

深藏阁楼爱情的钟 2022-01-30 02:57 266阅读 0赞

Given a range [m, n] where 0 <= m <= n <= 2147483647, return the bitwise AND of all numbers in this range, inclusive.

Example 1:

  1. Input: [5,7]
  2. Output: 4

Example 2:

  1. Input: [0,1]
  2. Output: 0

题目大意:

给出一个区间,我们需要求出其中全部的数进行或运算之后的结果。

解题思路:

我们发现如果某一列中存在一个0即该处的最终结果为0,所以我们需要找出这些数前部分的公共部分。

再将这个数右移。

  1. class Solution {
  2. public:
  3. int rangeBitwiseAnd(int m, int n) {
  4. int step = 0;
  5. while(m!=n){
  6. m>>=1;
  7. n>>=1;
  8. step++;
  9. }
  10. return n<<step;
  11. }
  12. };

发表评论

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

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

相关阅读