reverse-integer-2.cpp (533B)
1 class Solution { 2 public: 3 int reverse(int x) { 4 5 int result = 0; 6 bool positive = true; 7 8 if (x < -INT_MAX) return 0; 9 10 if (x < 0) positive = false, x *= -1; 11 12 while (x > 0) { 13 int residual = x % 10; 14 x /= 10; 15 int prior_result = result; 16 17 if (INT_MAX / 10 < result) return 0; 18 19 result *= 10; 20 result += residual; 21 } 22 23 if (!positive) { 24 result *= -1; 25 } 26 27 return result; 28 } 29 };