# C#LeetCode刷题之#7-反转整数（Reverse Integer）

Given a 32-bit signed integer, reverse digits of an integer.

Input: 123

Output: 321

Input: -123

Output: -321

Input: 120

Output: 21

Note:

Assume we are dealing with an environment which 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.

```public class Program {

private const string NEGATIVE_CHAR = "-";

public static void Main(string[] args) {
var x = 123;

var res = Reverse(x);
Console.WriteLine(res);

x = -567;
res = Reverse2(x);
Console.WriteLine(res);

}

private static int Reverse(int x) {
int.TryParse(ReverseString(x.ToString()), out int res);
return res;
}

private static string ReverseString(string text) {
var negative = text.StartsWith(NEGATIVE_CHAR);
var arr = text.Replace(NEGATIVE_CHAR, "").ToCharArray();
Array.Reverse(arr);
return (negative ? NEGATIVE_CHAR : "") + new string(arr);
}

private static int Reverse2(int x) {
var res = 0L;
while(x != 0) {
res = res * 10 + x % 10;
x = x / 10;
}
if(res > int.MaxValue || res < int.MinValue) {
res = 0;
}
return (int)res;
}

}```

```321
-765```