public class Solution { public int Reverse(int x) { int fuhao = 1; if (x < 0) { fuhao = -1; } try { x = Math.Abs(x); } catch (Exception e) { return 0; } int i = 0; var list = new List<long>(); do { long num = x % Convert.ToInt64(Math.Pow(10, i + 1)) / Convert.ToInt64(Math.Pow(10, i)); list.Add(num); i++; } while (x / Convert.ToInt64(Math.Pow(10, i)) != 0); var length = list.Count; long result = 0; for (int j = 0; j < length; j++) { try { result += list[j] * Convert.ToInt64(Math.Pow(10, length - j - 1)); } catch (Exception e) { result = 0; break; } } result *= fuhao; int res = 0; int.TryParse(result.ToString(), out res); //Console.WriteLine(res); return res; } }
https://leetcode.com/problems/reverse-integer/#/description
补充一个python的实现:
1 class Solution: 2 def reverse(self, x: int) -> int: 3 if x == 0: 4 return 0 5 operation = 1 6 if x < 0: 7 operation = -1 8 sx = str(x) 9 if sx[0] == '-': 10 sx = sx[1:] 11 n = len(sx) 12 result = [] 13 for i in range(n-1,-1,-1): 14 result.append(sx[i]) 15 r = int(''.join(result)) 16 r *= operation 17 if r >= 2 ** 31 or r < (-2) ** 31: 18 r = 0 19 return r