Determine whether an integer is a palindrome. Do this without extra space.
Click to show spoilers.
Some hints:
Cocould negative integers be palindromes? (Ie,-1)
If you are thinking of converting the integer to string, note the restriction of using extra space.
You cocould also try reversing an integer. However, if you have solved the problem "reverse integer", you know that the reversed integer might overflow. How wocould you handle such case?
There is a more generic way of solving this problem.
Determine whether the first and last digits are equal each time. If the first and last digits are equal, remove the first and last digits and continue the comparison until the end. Note that there may be 0 in the middle.
Class solution {public: bool ispalindrome (int x) {If (x <0) return false; int x0, xlen; // The first and last digits of X int xcopy = X; int Weight = 1; while (xcopy> = 10) {xcopy/= 10; weight * = 10;} xcopy = x; while (xcopy> = 10) {x0 = xcopy % 10; xlen = xcopy/weight; If (X0 = xlen) {// if equal, remove the start and end numbers xcopy-= (x0 + xlen * weight); xcopy/= 10; weight/= 100; If (xcopy = 0) return true; else if (xcopy <weight) {// prevents int weigh from being 0 in the middle Tnew = 1; int xcopy0 = xcopy; while (xcopy0> = 10) {xcopy0/= 10; weightnew * = 10;} int numzero = 1; int weightnew1 = weightnew * 10; while (weightnew1! = Weight) {// start with 0 weightnew1 * = 10; numzero ++;} while (numzero) {// if the end is not 0, false if (xcopy % 10! = 0) return false; else {xcopy/= 10; weight/= 100; numzero -- ;}}} else return false;} // end while return true ;} // end func };