-
Notifications
You must be signed in to change notification settings - Fork 0
/
PalindromeCheck.java
84 lines (70 loc) · 1.87 KB
/
PalindromeCheck.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
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
package math.easy;
/***
* Problem 9 in Leetcode: https://leetcode.com/problems/palindrome-number/
*
* Given an integer x, return true if x is palindrome integer.
* An integer is a palindrome when it reads the same backward as forward.
* For example, 121 is a palindrome while 123 is not.
*
* Example 1:
* Input: x = 121
* Output: true
*
* Example 2:
* Input: x = -121
* Output: false
*
* Example 3:
* Input: x = 10
* Output: false
*/
public class PalindromeCheck {
public static void main(String[] args) {
int num = 121;
System.out.println("Brute Force: " + palindromeCheckBruteForce(num));
System.out.println("String: " + palindromeCheckString(num));
System.out.println("Half reverse: " + palindromeCheckHalfReverse(num));
}
private static boolean palindromeCheckBruteForce(int num) {
if (num < 0) {
return false;
}
int temp = num;
int sum = 0;
while (temp > 0) {
sum = sum * 10 + (temp % 10);
temp /= 10;
}
return (sum == num);
}
private static boolean palindromeCheckString(int num) {
if (num < 0) {
return false;
}
String str = Integer.toString(num);
int n = str.length();
if (n == 1) {
return true;
}
for (int i = 0; i < n / 2; i++) {
if (!(str.charAt(i) == str.charAt(n - i - 1))) {
return false;
}
}
return true;
}
private static boolean palindromeCheckHalfReverse(int num) {
if (num < 0) {
return false;
}
if (num % 10 == 0 && num != 0) {
return false;
}
int sum = 0;
while (sum < num) {
sum = sum * 10 + (num % 10);
num /= 10;
}
return (num == sum || num == sum / 10);
}
}