From caafc3ccc51f83feffd89c5d683bef569b7479ba Mon Sep 17 00:00:00 2001 From: HoaPhan Date: Mon, 18 Mar 2024 03:09:24 +1100 Subject: [PATCH] https://leetcode.com/problems/reverse-integer/submissions/1206449247/ --- .../reverse_integer/Solution.java | 27 +++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 interview_prep/algorithm/java/ide_handicapped/reverse_integer/Solution.java diff --git a/interview_prep/algorithm/java/ide_handicapped/reverse_integer/Solution.java b/interview_prep/algorithm/java/ide_handicapped/reverse_integer/Solution.java new file mode 100644 index 0000000..8b24605 --- /dev/null +++ b/interview_prep/algorithm/java/ide_handicapped/reverse_integer/Solution.java @@ -0,0 +1,27 @@ +class Solution { + public int reverse(int x) { + int sign = x > 0 ? 1 : -1; + x *= sign; + int reversedNumber = 0; + while(x > 0) { + int digit = x % 10; + int newNumber = reversedNumber * 10 + digit; + if((newNumber - digit) / 10 != reversedNumber) { + return 0; + } else { + reversedNumber = newNumber; + } + x /= 10; + } + return reversedNumber * sign; + } + + public static void main(String[] args) { + //https://leetcode.com/problems/reverse-integer/description/ + final Solution sol = new Solution(); + assert sol.reverse(123) == 321; + assert sol.reverse(-123) == -321; + assert sol.reverse(120) == 21; + assert sol.reverse(-120) == -21; + } +} \ No newline at end of file