Leetcode 9. Palindrome number (judging palindrome numbers)

Source: Internet
Author: User

Determine whether an integer is a palindrome. Do the without extra space. (Do not use additional spaces)

Some hints:

Could negative integers be palindromes? (ie,-1)

If you is thinking of converting the integer to string, note the restriction of using extra space.

You could also try reversing an integer. However, if you had solved the problem "Reverse integer", you know that the reversed integer might overflow. How do would handle such case?

There is a more generic the solving this problem.

Analysis:

Palindrome number, and the topic requires that no extra space can be used.

That is, you cannot use a palindrome string method.

The subject is very simple, calculate the inverse of x A, compare a and X is equal to the line.

1 classSolution {2  Public:3     BOOLIspalindrome (intx) {4         //figure out the inverse of x a, and compare whether a is equal to X .5         intA =0, B =x;6          while(B >0){7A = A *Ten+ b%Ten;8b/=Ten;9         }Ten         if(A = =x) One             return true; A         Else -             return false; -          the     } -};

Other code on the net, its idea: each time to extract the head and tail two number, judge whether they are equal, judge to turn tail two number

1 classSolution {2  Public:3     BOOLIspalindrome (intx) {4         5         //Negative number6         if(X <0)7             return false;8             9         intLen =1;Ten          while(X/len >=Ten) OneLen *=Ten; A              -          while(X >0)    { -              the             //get the head and tail number -             intleft = x/Len; -             intright = x%Ten; -              +             if(Left! =Right ) -                 return false; +             Else    { A                 //remove the head and tail number atx = (x% len)/Ten; -Len/= -; -             } -         } -          -         return true; in     } -};

Leetcode 9. Palindrome number (judging palindrome numbers)

Related Article

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.