Write a program to check whether the given number is a power of 2 or not . For example if the given number is 8 then it should print true else if the given number is 7 then it should print false.
To check whether a number is a power of 2 we apply the and(&) operation between number(n) and number-1(n-1) if we get 0 then it is a power of 2 otherwise it is not .
To check whether a number is a power of 2 we apply the and(&) operation between number(n) and number-1(n-1) if we get 0 then it is a power of 2 otherwise it is not .
for example : Lets suppose given number is 8. then apply And operation on it.
(8-1) 7 = 0 1 1 1
------------- --------------------------------
AND OP = 0 0 0 0
------------------------------------------------
Hence 8 is a power of 2 . Similarly you can check for other numbers.
Implementation :
public class PowerofTwo {
public static void main(String args[])
{
int num = 7;
checkingPowerof2(num);
}
private static void checkingPowerof2(int num) {
// applying &
operation on n and n-1
if ((num & (num -
1)) == 0) {
System.out.println("true");
}
else {
System.out.println("false");
}
}
}
Please comment if you like the above post or if you find any mistake.
No comments:
Post a Comment