看起来很简单的样子,难点是判断是否溢出。但是c#丽是直接利用int.TryParse()来判断,所以直接把数字转为字符串,进行反转,在判断即可。
public int Reverse(int x)
{
string s1 = x.ToString();
string s2 = null;
if(x < 0)
{
s2 += '-';
for (int i = s1.Length - 1; i > 0; i--)//反转负数
{
s2 += s1[i];
}
}
else
{
for (int i = s1.Length - 1; i > -1; i--)//反转正数
{
s2 += s1[i];
}
}
if (int.TryParse(s2, out int result))//尝试转换
{
return result;
}
else
{
return 0;
}
}