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.
Here, Python’s handling of integers doesn’t actively overflow and actually causes problems, requiring special handling.
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.
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
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.
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
- 206. Reverse Linked List [easy] (Python)
- Leetcode: 7. Reverse Integer(JAVA)
- 21. Merge Two Sorted Lists [easy] (Python)
- matlab Error Subscript indices must either be real positive integers or logicals.
- Codeworks educational round 96 [reverse pair] E. string reverse
- Leetcode 832. Flip image
- [leetcode] 295. Find Median from Data Stream Python
- Develop a Boolean equation for overflow detection
- How to Use the Reverse() Function
- Can’t multiply sequence by non int of type ‘float’
- Use of rep function in R
- The usage of Matlab function downsample
- ValueError: Integers to negative integer powers are not allowed.
- In Java, int is converted to string, and zero is added before the number of bits is insufficient
- C++ string substr()
- Python: How to Fix “Ord() expected string of length 1, but int found”
- Definition of bracket type in typescript
- The usage of several integer functions in MATLAB (fix, floor, ceil, round)