-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPalindrome.java
More file actions
71 lines (58 loc) · 2.06 KB
/
Palindrome.java
File metadata and controls
71 lines (58 loc) · 2.06 KB
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
package Programming_Challenges;
import java.util.Scanner;
public class Palindrome {
// Method 1: Check if a number is a palindrome
public static boolean NumberPalindrome(int number) {
int original = number;
int reversed = 0;
// reverse the number
while (number != 0) {
int digit = number % 10;
reversed = reversed * 10 + digit;
number /= 10;
}
// return true if palindrome
return original == reversed;
}
// Method 2: Check if a word is a palindrome
public static boolean WordPalindrome(String word) {
word = word.toLowerCase();
int length = word.length();
for (int i = 0; i < length / 2; i++) {
if (word.charAt(i) != word.charAt(length - 1 - i)) {
return false; // not palindrome
}
}
return true; // palindrome
}
// Main method: where we test everything
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Choose type to check:");
System.out.println("1. Number");
System.out.println("2. Word");
System.out.print("Enter choice: ");
int choice = input.nextInt();
input.nextLine(); // consume newline
if (choice == 1) {
System.out.print("Enter a number: ");
int num = input.nextInt();
if (NumberPalindrome(num)) {
System.out.println(num + " is a palindrome number.");
} else {
System.out.println(num + " is not a palindrome number.");
}
} else if (choice == 2) {
System.out.print("Enter a word: ");
String word = input.nextLine();
if (WordPalindrome(word)) {
System.out.println(word + " is a palindrome word.");
} else {
System.out.println(word + " is not a palindrome word.");
}
} else {
System.out.println("Invalid choice.");
}
input.close();
}
}