7. Reverse Integer

Source: Internet
Author: User

https://leetcode.com/problems/reverse-integer/description/
Title: Give an Integer that returns the integer in reverse of each position.
Solution idea: initial old = 0, take the lowest bit tail of the integer n each time, and then build a new integer from low to high--------* + tail. After obtaining tail, remove the lowest bit of N, N=N/10, into the next round until n=0.
Note In order to avoid overflow, each time you record old and new, and then use the opposite method: Old = (new-tail)/10, to determine whether old and new are equal, if not equal before, indicating overflow.

Code:

Class Solution {public
:
    int reverse (int x) {
        int result = 0;
        while (x! = 0) {
            int tail = x Ten;
            int Newresult = result * + tail;
            if ((newresult-tail)/ten! = result) return 0;
            x/=;
            result = Newresult;
        }
        return result;
    }
;

Python implementation: Basically the same as the C language, the difference is that the negative number modulo and division need special treatment, which is simplified to first use positive processing, and then converted to negative numbers. Also be aware of the overflow, because Python's integer type range seems larger than the C language, so do not use the above practice to determine overflow, directly check whether [ -2^31, 2^31-1] can

class solution:def reverse (self, X): "" ": Type X:int:rtype:int "" "result = 0 while x! = 0:if x > 0:tail = x% El          
            Se:tail =-(-x%) #考虑负数处理 Newresult = result * + tail If x > 0:x//= else:x =-(-x//) #考虑负数处理 result = NEWR Esult if result < 2**31-1 and result > -2**31:return result else:return 0 

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.