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