-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathReverse.java
34 lines (32 loc) · 958 Bytes
/
Reverse.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
package com.aniketh;
// This code also contains palindromic number proof using recursion.
public class Reverse {
public static void main(String[] args) {
System.out.println(palindrome(1));
}
static int sum = 0;
static void rev1(int n) {
if (n == 0) {
return;
}
int rem = n%10;
sum = sum * 10 + rem;
rev1(n/10);
}
static int rev2(int n) {
// Sometimes you might need some additional variables in the arguments.
// In that case, make another function.
int digits = (int)(Math.log10(n)) + 1;
return helper(n, digits);
}
static int helper(int n, int digits) {
if (n%10 == 0) {
return n;
}
int rem = n % 10;
return rem * (int)(Math.pow(10, digits-1)) + helper(n/10, digits-1);
}
static boolean palindrome(int n) {
return n == rev2(n);
}
}