一次过
1 class Solution { 2 public: 3 int reverse(int x) { 4 // Start typing your C/C++ solution below 5 // DO NOT write int main() function 6 bool isNeg = x < 0; 7 x = abs(x); 8 int ret = 0; 9 while (x) { 10 ret = ret * 10 + x % 10; 11 x /= 10; 12 } 13 return isNeg? -ret : ret; 14 } 15 };
C#
1 public class Solution { 2 public int Reverse(int x) { 3 bool neg = x < 0; 4 if (x == Int32.MinValue) x = Int32.MaxValue; 5 else x = Math.Abs(x); 6 int ans = 0; 7 while (x > 0) { 8 if (ans > (Int32.MaxValue - x % 10) / 10) return 0; 9 ans = ans * 10 + x % 10; 10 x /= 10; 11 } 12 return neg? -ans : ans; 13 } 14 }