From 0ef7a50a290f46a3730e8b5ab7f184313344cdf6 Mon Sep 17 00:00:00 2001 From: Niu Date: Mon, 25 May 2015 17:18:31 +0800 Subject: [PATCH] improve the code The code is more concise. The submission result is accepted. --- c++/reverse-integer.cpp | 16 +++++----------- 1 file changed, 5 insertions(+), 11 deletions(-) diff --git a/c++/reverse-integer.cpp b/c++/reverse-integer.cpp index 47b616a..a432903 100644 --- a/c++/reverse-integer.cpp +++ b/c++/reverse-integer.cpp @@ -6,20 +6,14 @@ class Solution { -123 -> -321 100 -> 1 */ - - if (x < 0) { - return x == INT_MIN ? 0 : -reverse(-x); - } + int result = 0; - while (x > 0) { - if (result > INT_MAX / 10) { // will overflow - return 0; - } - if (result == INT_MAX / 10 && (x % 10) > 7) { // will overflow - return 0; - } + while (x != 0) { + if (result != 0 && INT_MAX / result < 10 + && INT_MAX / result > -10) + return 0; result = result * 10 + x % 10; x /= 10;