Topic link
https://leetcode.com/problems/reverse-integer/
The questions in the original
Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
The title translation
Reverses the number in an integer.
example 1: given x=123, return 321; Example 2: Given x=-123, return -321.
If x is equal to 10 or x is equal to 100, then both returns 1. 2. What happens to overflow after the original integer is reversed?– For example, if x=1000000003, reverse overflow, then the specified overflow results will return 0.
Thinking method
Here, Python’s handling of integers doesn’t actively overflow and actually causes problems, requiring special handling.
Thinking a
Loop through the modulus of 10 to get the tail number, step by step multiply 10 to construct a new flipped integer. However, it is important to first judge the positive and negative of the original number, and finally judge whether the result is overflow.
code
class Solution(object):
def reverse(self, x):
"""
:type x: int
:rtype: int
"""
flag = 1 if x >= 0 else -1
new_x, x = 0, abs(x)
while x:
new_x = 10 * new_x + x % 10
x /= 10
new_x = flag * new_x
return new_x if new_x < 2147483648 and new_x >= -2147483648 else 0
Idea 2
Python string reversal is used to reverse an integer, and the reversed string is converted back to an integer. As above, pay attention to positive and negative and overflow situations.
code
class Solution(object):
def reverse(self, x):
"""
:type x: int
:rtype: int
"""
x = int(str(x)[::-1]) if x >= 0 else - int(str(-x)[::-1])
return x if x < 2147483648 and x >= -2147483648 else 0
PS: The novice brush LeetCode, the new handwriting blog, write wrong or write unclear please help point out, thank you!
reprint please indicate the: http://blog.csdn.net/coder_orz/article/details/52039990
Read More:
- Leetcode: 7. Reverse Integer(JAVA)
- 206. Reverse Linked List [easy] (Python)
- Codeworks educational round 96 [reverse pair] E. string reverse
- How to Use the Reverse() Function
- 【Hackerrank】Reverse a doubly linked list
- Reverse function: reverses container contents
- Nginx reverse proxy MySQL
- IOS reverse error: use of undeclared identifier ‘mshookivar’
- Nginx reverse proxy report 400 error solution!
- Mybatis reverse problem failed to load ApplicationContext
- [Err] ERROR: invalid input syntax for integer: “1.0”
- ValueError: Integers to negative integer powers are not allowed.
- NxL job cluster nginx routing forwarding and reverse proxy
- The usage of several integer functions in MATLAB (fix, floor, ceil, round)
- error: aggregate value used where an integer was expected
- ISO C++ forbids comparison between pointer and integer [-fpermissive]
- There is no getter for property named ‘id‘ in ‘class java.lang.Integer‘
- The difference of four kinds of integer function (fix floor ceil round) in MATLAB
- Nginx front end and back end separation + service cluster reverse proxy
- Java long type error: error: integer number too large