From cd1e41aba5437aa7f4a2111e58bba963d9fead4f Mon Sep 17 00:00:00 2001 From: m-oliv Date: Thu, 4 Oct 2018 22:19:49 +0100 Subject: [PATCH] - Added the reverse integer algorithm. --- reverse/ReverseInteger.java | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 reverse/ReverseInteger.java diff --git a/reverse/ReverseInteger.java b/reverse/ReverseInteger.java new file mode 100644 index 00000000..4849fdd9 --- /dev/null +++ b/reverse/ReverseInteger.java @@ -0,0 +1,26 @@ +class ReverseInteger { + public static int reverse(int x) { + int reversed = 0; + int y = 0; + + while(x!=0){ + reversed = y * 10 + x % 10; + if((reversed - x % 10)/10 == y) { + y = reversed; + }else { + return 0; + } + x = x/10; + } + + if(x < 0) { + return y * -1; + } + + return y; + } + + public static void main(String[] args) { + System.out.println(reverse(12345)); + } +} \ No newline at end of file