加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

201. Bitwise AND of Numbers Range

发布时间:2020-12-14 05:14:26 所属栏目:大数据 来源:网络整理
导读:Given a range [m,n] where 0 = m = n = 2147483647,return the bitwise AND of all numbers in this range,inclusive. Example 1: Input: [5,7]Output: 4 Example 2: Input: [0,1]Output: 0 思路: and 的话必须两个都是1才是1. 先看最后一位。 101 110 111


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

Example 1:

Input: [5,7]
Output: 4

Example 2:

Input: [0,1]
Output: 0

思路:
and 的话必须两个都是1才是1.
先看最后一位。
101
110
111

抹掉,再看下一位
10
11
11
第一位,都是1,一共抹掉2个0,所以 1<<2
1
1
1

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读