[Leetcode] Palindrome Number validation palindrome numbers

Source: Internet
Author: User

Determine whether an integer is a palindrome. Do this without extra space.

Click to show spoilers.

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.

The problem of verifying palindrome numbers cannot use extra space, meaning that you cannot turn integers into characters and then validate palindrome strings. Instead of working directly on integers, we can use rounding and fetch Yu Lai to get the number we want, such as 1221, if we calculate 1221/1000, then we can get the first 1, if 1221 10, we can obtain the end 1, compare, then the middle 22 out to continue to compare. The code is as follows:

classSolution { Public:    BOOLIspalindrome (intx) {if(X <0)return false; intdiv =1;  while(X/div >=Ten) Div *=Ten;  while(X >0) {            intleft = x/Div; intright = x%Ten; if(Left! = right)return false; X= (x% div)/Ten; Div/= -; }        return true; }};

[Leetcode] Palindrome Number validation palindrome numbers

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.