Last active
August 29, 2015 14:04
-
-
Save bmchild/a83c5e371cf0cdf530c8 to your computer and use it in GitHub Desktop.
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
package com.bmchild.challenge.nine; | |
public class ChallengeNine { | |
private static final String PALINDROME = "Mr. Owl ate my metal worm"; | |
private static final String NOT_PALINDROME = "I am not a palindrome."; | |
public static void main(String[] args) { | |
checkPalindrome(PALINDROME); | |
checkPalindrome(NOT_PALINDROME); | |
for(int i = 0; i< 20; i++) { | |
checkPalindrome(Integer.toBinaryString(i)); | |
} | |
} | |
private static void checkPalindrome(String str) { | |
String stripped = stripChars(str); | |
String reversed = reverseChars(stripped); | |
if(reversed.equals(stripped)) { | |
System.out.println("'" + str + "' IS a palindrome"); | |
} else { | |
System.out.println("'" + str + "' is NOT a palindrome"); | |
} | |
} | |
private static String reverseChars(String stripped) { | |
return new StringBuilder(stripped).reverse().toString(); | |
} | |
private static String stripChars(String palindrome2) { | |
return palindrome2.replaceAll("[\\W]", "").toLowerCase(); | |
} | |
} | |
/* output is | |
'Mr. Owl ate my metal worm' IS a palindrome | |
'I am not a palindrome.' is NOT a palindrome | |
'0' IS a palindrome | |
'1' IS a palindrome | |
'10' is NOT a palindrome | |
'11' IS a palindrome | |
'100' is NOT a palindrome | |
'101' IS a palindrome | |
'110' is NOT a palindrome | |
'111' IS a palindrome | |
'1000' is NOT a palindrome | |
'1001' IS a palindrome | |
'1010' is NOT a palindrome | |
'1011' is NOT a palindrome | |
'1100' is NOT a palindrome | |
'1101' is NOT a palindrome | |
'1110' is NOT a palindrome | |
'1111' IS a palindrome | |
'10000' is NOT a palindrome | |
'10001' IS a palindrome | |
'10010' is NOT a palindrome | |
'10011' is NOT a palindrome | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment