class Solution {
public int reverse(int x) {
long n = 0;
while(x != 0){
n = n*10 + x % 10;
x = x / 10;
}
return (int)n ==n?(int)n:0;
}
}
This code is a method for reversing an integer. It accepts an integer x
as argument and returns its inverse result.
Inside the method, a long integer variable is first declared n
and initialized to 0. Then use a loop to iterate over x
each bit of the integer. In each loop, add the current digit n
to , and x
divide by 10 (dropping the last digit) to get the next digit.
After the loop ends, n
convert to an integer type and check if it is equal to the original n
. If they are equal, it means that no overflow has occurred and type conversion can be performed safely; otherwise, it means that overflow has occurred and the result needs to be set to 0. Finally, the reversed result is returned.
To sum up, the function of this code is to reverse the input integer x
and return the reversed integer value.
public int reverse(int x) {
long n = 0;
while(x != 0) {
n = n*10 + x%10;
x = x/10;
}
return (int)n==n? (int)n:0;
}
Attached is the link of the boss