Monday, October 27, 2014

Count the Number of Bits

Count the Number of Bits needed to be Flipped to Integer X to Generate Integer Y

#include 
#include 
#define num_bits_int (sizeof(int)*8)
 
void main()
{
    int n, m, i, count = 0, a, b;
 
    printf("Enter the number\n");
    scanf("%d", &n);
    printf("Enter another number\n");
    scanf("%d", &m);
    for (i = num_bits_int-1;i >= 0;i--)
    {
        a = (n >> i)& 1;
        b = (m >> i)& 1;
        if (a != b)
            count++;
    }
    printf("flip count = %d\n", count); 
    getch();
}

 
 
 
Output
 
Enter the number
127
Enter another number
125
flip count = 1
Enter the number
127
Enter another number
128
flip count = 8
Enter the number
42
Enter another number
21
flip count = 6

Identify the Missing Number in an Integer Array of Size N-1 with Numbers[1,N]

#include 
#include 
#define max 15
int missing_number_array(int [],int);
 
int main()
{
    int a[max], num, i, n;
    clrscr();
    printf("enter the range of array\n");
    scanf("%d", &n);
    for (i = 0;i < n;i++)
    {
        printf("enter a[%d]element into the array:", i);
        scanf("%d", &a[i]);
    }
    num = missing_number_array(a, n);
    printf("The missing number -> %d\n", num);
}
int missing_number_array(int a[],  int n)
{
    int i;
    int s1 = 0; 
    int s2 = 0; 
 
    for (i = 0;i < n;i++)
        s1 = s1 ^ a[i];
    for (i = 1;i <= n + 1;i++)
        s2 = s2 ^ i; 
    return (s1 ^ s2); 
    getch();
}
 
Output
 
enter the range of array
9
enter a[0]element into the array:1
enter a[1]element into the array:5
enter a[2]element into the array:2
enter a[3]element into the array:7
enter a[4]element into the array:3
enter a[5]element into the array:4
enter a[6]element into the array:10
enter a[7]element into the array:9
enter a[8]element into the array:6
The missing number -> 8
enter the range of array
4
enter a[0]element into the array:1
enter a[1]element into the array:5
enter a[2]element into the array:3
enter a[3]element into the array:2
The missing number -> 4
enter the range of array
4
enter a[0]element into the array:3
enter a[1]element into the array:2
enter a[2]element into the array:5
enter a[3]element into the array:4

The missing number -> 1

No comments:

Post a Comment