"Leetcode" "Python puzzle" Reverse Integer

Source: Internet
Author: User

Reverse digits of an integer.

Example1: x = 123, return 321
Example2: x = -123, return-321

Click to show spoilers.

Has a thought about this ?

Here is some good questions to ask before coding. Bonus points for if you have already thought through this!

If the last digit are 0, what should the output being?

ie, cases such as 10, 100.

Did you notice that the reversed integer might overflow? Assume the input is a 32-bit integer and then the reverse of 1000000003 overflows. How should handle such cases?

Throw an exception? Good, but what if throwing an exception was not an option? You would then has to re-design the function (ie, add an extra parameter).


The main idea is to flip an integer, but the two points need to be considered, one is the end is 0. The other is that it will be out of bounds after flipping, and the C + + codec may be cumbersome to handle, but Python is easy. directly to the STR type for processing. and calls the built-in function reverse, and when it goes int it takes its own initiative to handle 0 of the first band. Very easy. However, my program does not deal with the problem of cross-border. But still AC


Class solution:    # @return An integer    def reverse (self, x):        if x<0: Sign            =-1        else: sign            = 1
   STRX=STR (ABS (x))        r = strx[::-1]        return Sign*int (R)


"Leetcode" "Python puzzle" Reverse Integer

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.