This repository has been archived by the owner on Oct 14, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 249
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Create PalindromeChecker.java (#513)
- Loading branch information
Showing
1 changed file
with
41 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,41 @@ | ||
import java.util.Scanner; | ||
|
||
public class PalindromeChecker { | ||
|
||
public static void main(String args[]){ | ||
|
||
// Get number from user | ||
System.out.println("Enter a number : "); | ||
int x = new Scanner(System.in).nextInt(); | ||
|
||
// Check if x is palindrome | ||
if(isPalindrome(x)){ | ||
System.out.println(x + " is a palindrome"); | ||
}else{ | ||
System.out.println(x + " is not a palindrome"); | ||
} | ||
} | ||
|
||
// Given an integer x, return true if x is palindrome integer | ||
public static boolean isPalindrome(int x) { | ||
// Negative numbers can not be palindrome | ||
if (x < 0) return false; | ||
// 1-digit numbers are palindrome | ||
if (x < 10) return true; | ||
|
||
int palindrome = x; | ||
int reverse = 0; | ||
|
||
// The reverse of given x | ||
while (palindrome != 0) { | ||
int remainder = palindrome % 10; | ||
reverse *= 10 + remainder; | ||
palindrome /= 10; | ||
} | ||
|
||
// if x and reversed x is equal, return true | ||
if (x == reverse) | ||
return true; | ||
return false; | ||
} | ||
} |