“This is the 11th day of my participation in the Gwen Challenge in November. See details: The Last Gwen Challenge in 2021”
See: integer inversionLeetCode the original
Given a signed 32-bit integer x, return x with its digits reversed. If reversing x causes the value to go outside the signed 32-bit integer range [-231, 231-1), then return 0. Assume the environment does not allow you to store 64-bit integers (signed or unsigned). Example 1: Input: x = 123 Output: 321 Example 2: Input: x = -123 Output: -321 Example 3: Input: x = 120 Output: 21 Example 4: Input: x = 0 Output: 0 Constraints: -231 <= x <= 231 - 1Copy the code
Demand analysis
Testers still like to use requirements analysis
- Integers are allowed with signs, that is, negative integers
- Integer range [−231, 231 − 1] reversed, otherwise 0 is returned;
Their thinking
This time, first talk about ideas, then in the code, and finally in the analysis of the code
- It is still customary to turn it into a string and reverse it
- So the question is, there are many ways to reverse a string
Code implementation
class Solution:
def reverse(self, num: int) - >int:
num_str=str(num)
subx="-"
new_str=subx+num_str[1:] [: : -1] if subx in num_str else num_str[::-1]
new_num=int(new_str)
return 0 if new_num<-2**31 or new_num>2**31-1 else new_num
Copy the code
The result is as follows
The code analysis
Because the question allows negative integers, the author uses the “-” symbol as a separate judgment
- From the execution result, the execution speed is ok
- String inversion method, using slice [::-1] to invert
Algorithm optimization – from the official solution
It looks like you can go further and get the result without using string conversions;
Do you remember the palindrome number? With the while loop, it starts with the mantissa, but it only gets halfway there. So this problem needs to be completed from the end to the end.
While condition entry, x! = 0:
y=1234567 tmp=0 while y ! = 0: tmp=y%10+tmp*10 y//=10 print(tmp) # 7654321Copy the code
But it doesn’t support negative integers, so it needs special handling; And then the // of a negative integer is a positive integer,
y=-123 tmp=0 while y ! = 0: Dig =y%10 if y<0 and dig>0:# dig-=10 y=(y-dig)//10 TMP = TMP *10+dig res= 0 if TMP <-2**31 or TMP >2**31-1 else print(tmp) # -321Copy the code
The result is as follows
conclusion
From the execution result, it seems that the trickery is better and easier to understand. The official computation complexity seems to be slightly higher and belongs to pure numerical computation.
But anyway, the most important thing is to solve the problem thinking to clear, in order to give the answer, otherwise will fall into their own thinking trap unable to extricate themselves.