From 86f62dc8b20031c87317f5a820f2dd42bf05c3bf Mon Sep 17 00:00:00 2001 From: Nimesh Srivastava <30381993+Nimesh-Srivastava@users.noreply.github.com> Date: Fri, 27 Aug 2021 20:26:11 +0530 Subject: [PATCH 1/2] Fastest solution Executes in 0ms time, uses 5.9MB of storage --- C++/reverse-integer.cpp | 24 ++++++++++-------------- 1 file changed, 10 insertions(+), 14 deletions(-) diff --git a/C++/reverse-integer.cpp b/C++/reverse-integer.cpp index d181c1ca71..930742fd1f 100644 --- a/C++/reverse-integer.cpp +++ b/C++/reverse-integer.cpp @@ -4,20 +4,16 @@ class Solution { public: int reverse(int x) { - int result = 0; - while (x) { - if (result > numeric_limits::max() / 10 || - (result == numeric_limits::max() / 10 && x % 10 > numeric_limits::max() % 10)) { - return 0; - } - if (result < numeric_limits::min() / 10 || - (result == numeric_limits::min() / 10 && x % 10 < numeric_limits::min() % 10)) { - return 0; - } - result *= 10; - result += x % 10; - x /= 10; + long long ans = 0; + + if(x/10 == 0) + return x; + + while(x){ + ans = ans*10 + x%10; + x = x/10; } - return result; + + return (ans > INT_MAX || ans < INT_MIN) ? 0 : ans; } }; From 9ec8b1f2efc47214a94fda0e67eea1aefc9b8363 Mon Sep 17 00:00:00 2001 From: Nimesh Srivastava <30381993+Nimesh-Srivastava@users.noreply.github.com> Date: Sat, 28 Aug 2021 01:14:42 +0530 Subject: [PATCH 2/2] Update reverse-integer.cpp --- C++/reverse-integer.cpp | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/C++/reverse-integer.cpp b/C++/reverse-integer.cpp index 930742fd1f..70ea5874e9 100644 --- a/C++/reverse-integer.cpp +++ b/C++/reverse-integer.cpp @@ -2,6 +2,29 @@ // Space: O(1) class Solution { +public: + int reverse(int x) { + int result = 0; + while (x) { + if (result > numeric_limits::max() / 10 || + (result == numeric_limits::max() / 10 && x % 10 > numeric_limits::max() % 10)) { + return 0; + } + if (result < numeric_limits::min() / 10 || + (result == numeric_limits::min() / 10 && x % 10 < numeric_limits::min() % 10)) { + return 0; + } + result *= 10; + result += x % 10; + x /= 10; + } + return result; + } +}; + + +//Time : O(1) +class Solution2 { public: int reverse(int x) { long long ans = 0;