[Leetcode] palindrome number

Source: Internet
Author: User

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 };

 

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.