Amazon Interview Question
Software Engineer / Developerspublic class Main {
/**
* @param args the command line arguments
*/
public static void main(String[] args) throws IOException {
BufferedReader reader=new BufferedReader(
new InputStreamReader(System.in) );
while(true)
{
System.out.print("input integer:");
String line= reader.readLine();
if(line.isEmpty())
{
break;
}
int digit=Integer.parseInt(line);
System.out.println("processing : "+ digit );
boolean isP=checkPowerOf2(digit);
if(isP)
{
System.out.println(digit+" is power of 2");
}else
{
System.out.println(digit+" is NOT power of 2");
}
}
reader.close();
}
private static boolean checkPowerOf2(int digit) {
long p2=2;
while(true)
{
if(p2>digit)
{
return true;
}
if(digit%p2!=0)
{
return false;
}
p2*=2;
}
}
}
@sarathprasath: it looks like O(1).
counting bits is faster than applying '&' between two bits. If you look into the details "num & (num-1) == 1" has more complexity than counting number of bits
The person who posted the question has given answer in O(1) time complexity. I don't know, why HertzLee answered it differently.
Sorry but could you please explain how it works? Could not understand the logic behind it. Any inputs would be of great help. Thanks
For all the folks who think the answer posted with the question is right: IT IS PLAIN WRONG.
As Tulley pointed out it should be "if((num) && (!(num & num-1))"
But looking at blueskin's solution: counting number of bits and if equals to 1 or break counting when greater than 1 is the best solution because counting bits is faster than applying bit operations between two integers
public static void main(String[] args) {
- yashddn March 05, 2011// TODO Auto-generated method stub
for(int i = 2 ; i < 10000; i++) {
int j = i&(i-1);
if(j == 0) {
System.out.println("2s Power:: "+i);
}
}
}