7. Reverse Integer
Given a 32-bit signed integer, reverse digits of an integer.
Note: Assume we are dealing with an environment that could only store integers within the 32-bit signed integer range: [−231, 231 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
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 - 1
public class Solution {
public int Reverse(int x) {
if(x == 0){
return 0;
}
string new_string = NewString(x);
int new_int = Conver(new_string);
if(new_int == 0){
return 0;
}
if(x < 0){
return (-new_int) < Int32.MinValue ? 0 : (-new_int);
}
else{
return new_int > Int32.MaxValue ? 0 : new_int;
}
}
public string NewString(int x){
string orgin = x.ToString();
char[] c = orgin.ToCharArray();
if(x < 0){
c = c.Skip(1).ToArray();
}
Array.Reverse(c);
string new_s = new String(c);
return new_s;
}
public int Conver(string x){
int new_x;
bool isParse = Int32.TryParse(x, out new_x);
if(isParse){
return new_x;
}
return 0;
}
}
Last updated
Was this helpful?