c++ - To check whether an integer is a palindrome in O(1) space(Wrong answer) -


i tried solving question reversing number ,using bitwise operations:- example if number's binary representation 00000110 ,what code is, send 0000011 code , left shift reverse_num 5 times 01100000, reverse of original,after program "&" of number original number.if answer 1 ,then number said palindrome else false returned.is there flaw in logic? if there ,i think it's in & part.

class solution { public:     bool ispalindrome(int x) {         if(x<0)             return false;         int num=x;         int reverse_num=x;         int count=sizeof(x);         num >>= 1;         while(num)             {                 reverse_num <<= 1;                       reverse_num |= num & 1;                 num >>= 1;                 count--;             }         reverse_num <<= count;          if(!(reverse_num&x))             return true;         else return false;     } }; 

i still want know wrong previous code . sorry asking such silly question .i noob in programming. original question here:https://oj.leetcode.com/problems/palindrome-number/

although able around question doing this:

class solution { public:     bool ispalindrome(int x) {         long long y=0;         long long t=x;         long long p;         p=x;         while(t){             y=y*10+t%10;             t=t/10;         }         if(p==y && p>=0)             return true;         else return false;      }  }; 

for final if statement, && logical and. in c/c++ (and many other languages), logical test on integer return true unless value 0.

so function return true if either x or reverse_num 0


Comments

Popular posts from this blog

c++ - OpenCV Error: Assertion failed <scn == 3 ::scn == 4> in unknown function, -

php - render data via PDO::FETCH_FUNC vs loop -

The canvas has been tainted by cross-origin data in chrome only -