Check if All the Bits of a
given Integer is One
#include
#include
int all_bits_one(int);
int count = 0;
void main()
{
int num;
printf("enter the number:");
scanf("%d", &num);
num++;
all_bits_one(num);
if (count)
{
printf("false");
}
else
{
printf("true");
}
}
int all_bits_one(int x)
{
if (x == 1)
return 0;
if (x % 2 != 0)
{
count++;
}
else
{
x = x / 2;
all_bits_one(x);
}
getch();
}
Output
Enter the number:5
False
Enter the number:7
True
Enter the number:127
True
Enter the number:125
False
Find Next higher Value of N with same
1′s
#define num_bits_int 32
#include
#include
int newcount(int);
void main()
{
int count1 = 0, k = 0, j, t, n, bit, i = 1, count = 0;
clrscr();
printf("Enter a number : ");
scanf("%d", &n);
t = n;
while(t != 0)
{
bit = t & 0x80000000;
if (bit == -0x80000000)
{
bit = 1;
}
if (bit == 1)
count++;
t = t << 1;
}
for (k = n + 1;;k++)
{
count1 = newcount(k);
if (count1 == count)
{
printf("The next highest number is : %d ", k);
break;
}
}
}
int newcount(int k)
{
int bit, count = 0;
while (k != 0)
{
bit = k & 0x80000000;
if (bit == -0x80000000)
{
bit = 1;
}
if (bit == 1)
count++;
k = k << 1;
}
return(count);
getch();
}
Output
Enter a number: 128
The next highest number is: 256
Enter a number: 127
The next highest number is: 191
Enter a number: 6
The next highest number is: 9
Enter a number: 12
The next highest number is: 17
Count the Number of
Trailing Zeroes in Integer
#include
#include
void main()
{
int j = 31, i, count = 0;
unsigned int num;
int b[32] = {0};
clrscr();
printf("Enter the number:");
scanf("%d", &num);
while (num != 0)
{
if (num & 1 == 1)
{
break;
}
else
{
count++;
num = num >> 1;
}
}
printf("\n%d", count);
getch();
}
Output
Enter the number:128
7
Enter the number:-127
0
No comments:
Post a Comment