Last active
January 17, 2016 20:56
-
-
Save deyindra/d2b6280852712e02d9ad to your computer and use it in GitHub Desktop.
Check if the Binary Representation of a number is Palindrome or not
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static int countNumberofOneBit(int number){ | |
int count=0; | |
while (number!=0){ | |
count++; | |
number=(number-1)&number; | |
} | |
return count; | |
} | |
public static int countNumberofNonLeadingZeroBit(int number){ | |
int result=0; | |
while (number!=0){ | |
if((number & 1)==0){ | |
result++; | |
} | |
number >>>= 1; | |
} | |
return result; | |
} | |
public static boolean isSet(int number, int k){ | |
return ((number & (1<<k-1)) !=0); | |
} | |
public static boolean isPallindrome(int number){ | |
int totalBit = countNumberofOneBit(number)+countNumberofNonLeadingZeroBit(number); | |
int start=1; | |
while (start<totalBit){ | |
if(isSet(number,start) != isSet(number,totalBit)){ | |
return false; | |
} | |
start++; | |
totalBit--; | |
} | |
return true; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment