Leetcode 9 palindrome Number palindrome

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.

A very concise C + + solution:
Only half of the palindrome is compared.

 Public Boolean isPalindrome1(intx) {if(x = =0)return true;//In Leetcode, negative numbers and numbers with ending zeros    // is not palindrome    if(X <0|| X%Ten==0)return false;//Reverse half of the number    //The exit condition is y >= x    //So, overflow is avoided.    inty =0; while(Y < x) {y = y *Ten+ (x%Ten);if(x = = y)//To check numbers with odd digits            return true; X/=Ten; }returnx = = y;//To check numbers with even digits}

The solution for Python should be a comparison of before and after:

 class solution:    # @param x, an integer    # @return A Boolean     def ispalindrome(self, x):        ifX <0:return FalseRanger =1         whileX/ranger >=Ten: Ranger *=Ten         whileX:left = X/ranger right = x%Ten            ifLeft! = Right:return Falsex = (x% Ranger)/TenRanger/= -        return True

The solution to the Python string:

class Solution:    # @param {integer} x    # @return {boolean}    def isPalindrome(self, x):        return str(x)==str(x)[::-1]

Leetcode 9 palindrome Number palindrome

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.