0

Determine the number of 1-bit pairs without overlap with other pairs in C. But My code does not include the first number. Like 11011 has 2 pairs of 1-bit but my output gives me 1 pair because it did not include the first number.

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; } 
3
  • Why not mask with 11 and skip 2 bits if found (one if not)? Commented Mar 5, 2019 at 19:25
  • Did you mean to say prevOne=currOne? Why are you dividing by 2? Commented Mar 5, 2019 at 19:51
  • Could you edit your title or your text, as one talks about counting pairs, and one about counting the number of consecutive '1' which I would say is 4 for 1111, but it's only 2 pairs of '1'. And/or add another example of results expected for 11110111 Commented Mar 5, 2019 at 22:48

1 Answer 1

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. } 
Sign up to request clarification or add additional context in comments.

3 Comments

nice answer, However, we would like to be able to easily read/understand it. A major step in the understanding is if it were properly indented. Suggest 1) always include the optional braces '{}" 2) indent after every opening brace '{'. 3) unindent before every closing brace '}'. Suggest each indent level be 4 spaces
I usually indent my code. But could not find any efficient way of doing it when writing answer from android.
I modified your answer by inserting the appropriate indentation

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.