-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathPalindrome
100 lines (83 loc) · 1.83 KB
/
Palindrome
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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
// A recursive Java program to
// check whether a given number
// is palindrome or not
import java.io.*;
import java.util.*;
public class CheckPallindromNumberRecursion {
// A function that reurns true
// only if num contains one digit
public static int oneDigit(int num) {
if ((num >= 0) && (num < 10))
return 1;
else
return 0;
}
public static int isPalUtil
(int num, int dupNum) throws Exception {
// base condition to return once we
// move past first digit
if (num == 0) {
return dupNum;
} else {
dupNum = isPalUtil(num / 10, dupNum);
}
// Check for equality of first digit of
// num and dupNum
if (num % 10 == dupNum % 10) {
// if first digit values of num and
// dupNum are equal divide dupNum
// value by 10 to keep moving in sync
// with num.
return dupNum / 10;
} else {
// At position values are not
// matching throw exception and exit.
// no need to proceed further.
throw new Exception();
}
}
public static int isPal(int num)
throws Exception {
if (num < 0)
num = (-num);
int dupNum = (num);
return isPalUtil(num, dupNum);
}
public static void main(String args[]) {
int n = 1242;
try {
isPal(n);
System.out.println("Yes");
} catch (Exception e) {
System.out.println("No");
}
n = 1231;
try {
isPal(n);
System.out.println("Yes");
} catch (Exception e) {
System.out.println("No");
}
n = 12;
try {
isPal(n);
System.out.println("Yes");
} catch (Exception e) {
System.out.println("No");
}
n = 88;
try {
isPal(n);
System.out.println("Yes");
} catch (Exception e) {
System.out.println("No");
}
n = 8999;
try {
isPal(n);
System.out.println("Yes");
} catch (Exception e) {
System.out.println("No");
}
}
}