ALLInterview.com :: Home Page KalAajKal.com
 Advertise your Business Here     
Browse  |   Placement Papers  |   Company  |   Code Snippets  |   Certifications  |   Visa Questions
Post Question  |   Post Answer  |   My Panel  |   Search  |   Articles  |   Topics  |   ERRORS new
   Refer this Site  Refer This Site to Your Friends  Site Map  Bookmark this Site  Set it as your HomePage  Contact Us     Login  |  Sign Up                      
info       Did you received any Funny E-Mails from your Friends and like to share with rest of our friends? Yeah!! you can post that stuff   HERE
Google
 
Categories >> Code-Snippets >> Programming-Code >> C-Code
 
 
 
Question
Give a oneline C expression to test whether a number is a 
power of 2?
 Question Submitted By :: Solidcube
I also faced this Question!!     Rank Answer Posted By  
 
Answer
#include <stdio.h>
#include <stdlib.h>
#include <math.h>

bool isPowerOf2(int number){
	if ( number > 0 )
		return (number & (number-1)) == 0;
	
	if (number == 0)
		return false;
	
	if (isPowerOf2(-number)){
		int count=0;
		while ( !(number & 1)) {
			++count;
			number >>= 1;
		}
		if (fmod(count,2))
			return true;
		else
			return false;
	}
	return false;
}

int main(void) {
	for(int i=-1027; i<1025; ++i){
		if (isPowerOf2(i) )
			printf("%d\n", i);
	}
	
	return EXIT_SUCCESS;
}
 
0
Nmk
 
View All Answers
 
 
 
 
 
   
Copyright Policy  |  Terms of Service  |  Help  |  Site Map 1  |  Articles  |  Site Map  |   Site Map  |  Contact Us interview questions urls   External Links 
   
Copyright © 2007  ALLInterview.com.  All Rights Reserved.

ALLInterview.com   ::  Forum9.com   ::  KalAajKal.com