c# 版本c#
// 給定一個 32 位有符號整數,將整數中的數字進行反轉。
public class Solution
{
public int Reverse(int x)
{
/
// 邊界判斷
// x變成字符串,而後拼接字符串。
若是第一位是-,則將其放到第一位。
從後往前遍歷
若是遇到0則無視
/
if (x >= Int32.MaxValue || x < Int32.MinValue)
{
return 0;
}ui
StringBuilder sb1 = new StringBuilder(); string x_str = x.ToString(); if (x_str[0] == '-') { sb1.Append("-"); } bool start_not_zero = false; for (int i = x_str.Length - 1; i >= 0; i--) { if (i == 0 && x_str[i] == '-')// 第一位 { continue; } if (x_str[i] == 0 && start_not_zero == false)// 最後一位是0 { start_not_zero = false; continue; } else { start_not_zero = true; } sb1.Append(x_str[i]); } long x1 = Int64.Parse(sb1.ToString()); if (x1 >= Int32.MaxValue || x1 < Int32.MinValue) { return 0; } return (int)x1; } }