Implement the inspect_bits function that checks if given number contains 2 or more consecutive ones in its binary representation. If it does, the function should return 1. Otherwise, it should return 0.
For example, inspect_bits(13) should return 1 as it contains 2 consecutive ones in its binary representation (1101).
The program is working for certain numbers, 13 in this case, and a few others, however, the program is not working for '8','10' and for some other numbers.
#include <stdlib.h>
#include <stdio.h>
int inspect_bits(unsigned int number)
{
int arr[32];
int i=0,temp,c=0;;
while(number > 0)
{
arr[i] = number%2;
number = number/2;
i++;
}
for (int j=i-1; j>=0; j--)
{
temp = arr[j];
for (int k=j+1; k>0; k--)
{
if (temp==arr[k])
c++;
}
}
if (c != 0)
return 1;
else
return 0;
}
#ifndef RunTests
int main ()
{
printf("%d", inspect_bits(13));
}
#endif
That looks way too complicated, as an algorithm implementation and to debug. This is simpler:
int inspect_bits(unsigned int number)
{
while (number)
{
if ((number & 3) == 3)
return 1;
number >>= 1;
}
return 0;
}
The loop tests the last two bits of number
against 3, which is 00000011
in binary. If this matches, then there were (at least!) two consecutive bits in number
. If not, the bits in number
are shifted to the right and tested again. The loop can stop when number
reaches 0 -- technically even while (number > 2)
as only values higher than 2 have more than two consecutive bits.
To determine whether the unsigned integer n
has two adjacent bits set, it is enough to test:
(n & (n >> 1)) != 0
There n >> 1
is the number n
shifted one bit to the right, which is the same as an integer division by 2. You can visualize this method by numbering the bits:
n 7 6 5 4 3 2 1 0
n >> 1 7 6 5 4 3 2 1
The bitwise and ( &
) is a binary operator. Its result will have a bit set if both operands have the respective bit set. In the expression above, it will have bit 0 set if n
has both bit 0 and 1 set; it will have bit 1 set if n
has both bit 1 and 2 set and so on. It will have no bits set (and therefore be zero) if no two adjacent bits of n
are set.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.