计算连续的1位而不重叠

时间:2019-03-05 19:23:50

标签: c

确定不与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;
}

1 个答案:

答案 0 :(得分: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.
}