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 };
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。