LeetCode *** 201. Bitwise AND of Numbers Range

来源:互联网 发布:python tushare 实例 编辑:程序博客网 时间:2024/06/06 01:31
题目:

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.


分析:
最近的接受率直线下降。。。。醉了。。

代码:
class Solution {public:    int rangeBitwiseAnd(int m, int n) {        if(m==0)return 0;        int res=1;                while(m!=n){            m>>=1;            n>>=1;            res<<=1;        }        return res*m;    }};

class Solution {public:    int rangeBitwiseAnd(int m, int n) {        if(m==0)return 0;        if(m==n)return m;        int res=0,lm=0,ln=0,count=n-m+1,p=1,i=0;        int resbit[31]={0};                while(m&&n){            lm=(m&1);            ln=(n&1);            m>>=1,n>>=1;            if(!(!ln||!lm||(p<count)))resbit[i]=1;            i++;            p=p*2;        }                for(int i=30;i>=0;i--){            res<<=1;            res+=resbit[i];        }        return res;    }};

0 0
原创粉丝点击