Monday, October 27, 2014

Check whether the given Number is Palindrome or not using Bitwise Operator

Check whether the given Number is Palindrome or not using Bitwise Operator

#include 
#include 
#include 
#define size 8
int is_palindrome(unsigned char[]);
 
void main()
{
    int num, num1 = 0, i = 0, j = SIZE - 1, res;
    unsigned char c[size];
    clrscr();
    printf("Enter a number(max 255)");
    scanf("%d", &num);
    num1 = num;
    while (num != 0)
    {
        c[j] = num&1;
        j--;
        num = num>>1;
    }
    printf("The number %d in binary is:", num1);
    for (i = 0;i < size;i++)
    {
        printf("%d", c[i]);
    }
    res = is_palindrome(c);    
    if (res == 0)
    {
        printf("\n Number is palindrome\n");
    }
    else
    {
        printf("\n Number is not palindrome\n");
    }
}
 
int is_palindrome(unsigned char c[])
{
    char temp[size];
    int i, j, flag = 0;
    for (i = 0, j = size - 1;i < size, j >= 0;i++, j--)
    {
        temp[j] = c[i];
    }
    for (i = 0;i < size;i++)
    {
        if (temp[i] != c[i])
        {
            flag = 1;
        }
    }
    return flag;
}
 
Output
                   
                  Enter a number(max 255)153
The number 153 in binary is:10011001
Number is palindrome
 
Enter a number(max 255)24
The number 24 in binary is:00011000
Number is palindrome

Swap two Numbers using Bitwise Operators

#include 
#include 
#include 
 
void swap(int*, int *);
 
void main()
{
    int num1, num2;
    printf("\nEnter two numbers:");
    scanf("%d %d", &num1, &num2);
printf("\nThe numbers before swapping are Number1= %d Number2 = %d", num1, num2);
    swap(&num1, &num2);        
    printf("\nThe numbers after swapping are Number1= %d Number2 = %d", num1, num2);
}
 void swap(int *x, int *y)
{
    *x = *x ^ *y;
    *y = *x ^ *y;
    *x = *x ^ *y;
}

Output
 
Enter two numbers:45 76
The numbers before swapping are Number1= 45 Number2=76

The numbers after swapping are Number1= 76 Number2=45

No comments:

Post a Comment