Showing posts with label Bitwise Operators. Show all posts
Showing posts with label Bitwise Operators. Show all posts

Friday, June 5, 2009

2 to the power of N

Here is a one-liner statement to check if a given integer is of 2 to the power of N.

public static boolean twoPowerN(int x){
return ((x & -x) == x) ? true : false;
}
You may try the method using this test case:
System.out.println(twoPowerN((int) Math.pow(2, 8)));

Basically it returns true for all integers 2powN, for example 2^100 or 2^7 or 2^33. A false will be returned for values other than 2powN. Well, that's the purpose of this method anyway (to check if a method is 2 to the power of N), right? :)

Have a good day everyone!

Friday, May 29, 2009

Swapping 2 Integers

I believe many of us out there came across, at least once in their lifetime, the problem to swap two numbers. Here are the three sample solutions that I could think to swap two numbers.
Solution A:

temp = a;
a = b;
b = temp;
Solution A introduces an additional auxiliary variable called "temp" in the code to hold one of the values (either a or b) which increases the footprint of the compiled class.
Solution B:

a = a ^ b;
b = b ^ a;
a = a ^ b;
Solution B on the other side swaps two numbers using bitwise operation. The XOR (Exclusive OR) is introduced in this code.
Solution C:

a = a + b;
b = a - b;
a = a - b;
Last but not least, Solution C swaps two numbers using arithmetic operations, both addition and subtraction.
Conclusion: In terms of speed, I would personally rank Solution B being the fastest, Solution C the second fastest and Solution A the slowest. (B -> C -> A)