繁体   English   中英

计算连续的1位而不重叠

[英]Count the consecutive 1-bit without overlapping

确定不与C中其他对重叠的1位对的数量。但是我的代码不包括第一个数字。 像11011有2对1位,但是我的输出给我1对,因为它不包括第一个数字。

int numPairs(int n){
    int count=0;
    bool prevOne=0;
    while(n!=0){
        bool currOne=(n&1)==1;
        if(currOne && !prevOne)
            count++;
        n=n>>1;
        prevOne=!currOne;
    }
    return count/2;
}
int numPairs(int n)
{ 
    int count=0; 
    bool prevOne=0; // 1 if previous bit was 1.
    while(n!=0)
    { 
        bool currOne=(n&1)==1; 
        if(currOne && prevOne) 
            count++; 
        n=n>>1; 
        prevOne=currOne; 
    } 
    return count; // no need divide count by 2 as count exactly specifies number of 1bit pairs.
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM