C Project. -- I. ALTERNATING BITS Write a method that takes a sequence of bits e
ID: 3760328 • Letter: C
Question
C Project. -- I. ALTERNATING BITS
Write a method that takes a sequence of bits encoded in an unsigned integer variable, and tests whether this sequence is composed of alternating 1s and 0s (e.g., “1”, “10”, “101”, “1010”, “10101”). Your function will return two values: An integer that is either 1 or 0 depending on the test result. A return value of 1 implies an alternating sequence. If the test result is 1, the length of the sequence. Your function has to rely on bitwise operations: no multiplication or division! Include in your solution a test program that reads an unsigned integer and outputs the result
A. Example Run
./a.out
Enter an unsigned integer: 1
Alternating sequence of length 1.
./a.out
Enter an unsigned integer: 5
Alternating sequence of length 3
Explanation / Answer
Solution in C language is below:
#include <stdio.h>
unsigned int int_to_int(unsigned int k) {
return (k == 0 || k == 1 ? k : ((k % 2) + 10 * int_to_int(k / 2)));
}
int bitCount(unsigned int n) {
int counter = 0;
while(n) {
n = n >> 1;
counter++;
}
return counter;
}
int main()
{
int n;
printf("Enter an unsigned integer: ");
scanf("%d", &n);
printf("Bits Sequence is: %d ", int_to_int(n));
printf("Alternating sequence of length is: %d ", bitCount(n));
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.