palin

2
The idea is simple, we take two pointers one at leftmost bit and another at rightmost bit, extract bits information using the pointers both bits should either be 0 or 1. and move the pointers until they meet. Now how would you extract the bit is tricky one, basically you first get number of bits in the integer and then shift 1 left by (number of bits -1) this will become our leftmost pointer and number 1 will be our rightmost pointer. Use & operator between original number and these pointers if the result is 0 then the corresponding bit is zero else(non-zero) then corresponding bit is 1. Note: check for non-zero rather then > 0 as 1000000000000 will be negative. Here is the java code to get the size of the integer public int getSizeOfInteger(){ int size =1; int num =1; //shift the number untill it becomes negative(1 followed by 0's) while(num > 0){ num = num<<1; size++; } return size; } Here is the java code to get if the bit representation of the number is palindrome or not public boolean isPalindrome(int n){ int rightPointer =1; int leftPointer = 1<<(getSizeOfInteger()-1); int count = getSizeOfInteger()/2; while(count > 0){ //Checking if both bits are 0 or both are non-zero and then negate if( !(((n & leftPointer) != 0 && (n & rightPointer) != 0) || ( (n & leftPointer) == 0 && (n & rightPointer) == 0))){

Upload: venitia

Post on 18-Aug-2015

213 views

Category:

Documents


1 download

DESCRIPTION

java pgm

TRANSCRIPT

The idea is simple, we take two pointers one at leftmost bit and another at rightmost bit, extractbits information using the pointers both bits should either be 0 or 1. and move the pointers untilthey meet.Nowhow would you extract the bit is tricky one, basically you first get number of bits in theinteger and then shift 1 left by (number of bits -1 this will become our leftmost pointer andnumber1will beourrightmost pointer.!se"operatorbetweenoriginal numberandthesepointers if the result is 0 then the corresponding bit is #ero else(non-#ero then corresponding bitis 1.Note: check for non-#ero rather then $ 0 as 1000000000000 will be negative.%ere is the &ava code to get the si#e of the integerpublic int getSizeOfInteger(){int size =1;int num =1;//shift the number untill it becomes negative(1 followe b! "#s)while(num $ "){num = num%%1;size&&;'return size;'%ere is the &ava code to get if the bit representation of the number is palindrome or notpublic boolean is(alinrome(int n){int right(ointer =1;int left(ointer = 1%%(getSizeOfInteger())1);int count = getSizeOfInteger()/*;while(count $ "){//+hec,ing if both bits are " or both are non)zero an then negateif( -(((n . left(ointer) -= " .. (n . right(ointer) -= ") //( (n . left(ointer) == " .. (n . right(ointer) == "))){return false;//0oth bits are not same'count));'return true;'