algorithms

Check if Number is Odd Using Bitwise – C

An odd number always has the LSB set to 1. If we AND the given number with 1, the even number will always turn out to be zero. We can using this to check if the number is odd or even.

Examples:

1) n = 4

100     (4)
001     (1)
———– AND
000

2) n = 7

101    (7)
001    (1)
———— AND
001

C Program:

#include 

int main()
{
    int n = 11;
    int result = n & 1;
    if(result)
        printf("Odd number\n");
    else
        printf("Even number\n");

    return 0;
}

Advertisements

Let me Know What you Think!

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s