Showing posts with label Trickybits. Show all posts
Showing posts with label Trickybits. Show all posts

28.2.08

Swap the two numbers

This is the most frequently asked C question.

How to swap two numbers without using temporary variable.

There are many ways to do that, here are some.

Code snippets:
1)

int x, y; /* are the two numbers */
x = x+y;
y = x - y;
x = x - y;

2)
x = x*y;
y = x/y;
x = x/y;
3)
x = x ^ y;
y = x ^ y ;
x = x ^ y ;
NOTE: These logics have some limitations
Logic 1 has the Overflow problem when we add (x+y).
Logic 2 has the Overflow problem when we multiply ( x*y) and y should not be Zero.
Logic 3 has the same and its not works on the float numbers.

27.2.08

Even/Odd number

This is also one of the C Interview questions.

How to tell the given number is even or odd number in single line C code.

Code snippet:
int num;
num&1 ? printf("Odd Number\n") : printf("Even number\n");

Logic is every odd number will have least significant bit has 1
in binary representation of the number.

So when we do bitwise AND with number 1, obviously the
result is '1' for odd numbers and '0' for even numbers.

power of 2

This is one tricky bit usually asked in C interviews

How to tell the given number is Power of 2 or not in a one line 'C 'code.

There are many ways to do this, here is my logic.

Code snippet:

int num; /* holds the integer value */

num & (num-1) ? printf("Not Power of 2\n") : printf("Power of 2\n");