Hello friends,
I am here with you with a problem. I took the idea of this problem from a problem posted in geeksforgeeks : http://www.geeksforgeeks.org/check-if-a-given-number-is-fancy
A number is a special 180 degree palindrome if upon rotating it 180 degrees we get the same number back.
For example : 0, 1, 8, 96, 69, 906, 901106, 68089 are such numbers and 2,929,926,99,66,6,9 are not such special 180 degree palindrome numbers.
Please find below my solution in Java for this problem.
public class SpecialPalindrome { public static void main(String[] args) { System.out.println(isSpecialPalindrome(68111011189l)); } public static boolean isSpecialPalindrome(long N) { char arr[] = new Long(N).toString().toCharArray(); boolean isOddDigits = arr.length % 2 == 0 ? true : false; int loopRun = arr.length / 2; int n = arr.length; HashMap map = new HashMap(); map.put('0', '0'); map.put('1', '1'); map.put('8', '8'); map.put('6', '9'); map.put('9', '6'); int i = 0; for (; i < loopRun; i++) { char left = map.get(arr[i]); char right = map.get(arr[n-i-1]); if(left != ' ' && right != ' ' && left == arr[n-i-1]){ continue; }else{ return false; } } if (isOddDigits && map.get(arr[i]) == ' ') { return false; } return true; } public static class HashMap { private int prime = 499; MapNode[] map = new MapNode[prime]; private class MapNode { private MapNode next; char value; char key; public MapNode(MapNode next) { this.next = next; } public MapNode(char key, char value, MapNode next) { this.key = key; this.value = value; this.next = next; } } public void put(char key, char value) { int index = index(key); MapNode node = map[index]; while (node != null) { if (node.key == key) { node.value = value; // update the value return; } node = node.next; } map[index] = new MapNode(key, value, map[index]); } public int hashcode(char key) { return key * 31; } public int index(char key) { return hashcode(key) % prime; } public char get(char key) { int index = index(key); MapNode node = map[index]; while (node != null) { if (node.key == key) { return node.value; } node = node.next; } return ' '; } public boolean contains(char key){ int index = index(key); MapNode node = map[index]; while (node != null) { if (node.key == key) { return true; } node = node.next; } return false; } } }
No comments:
Post a Comment
Hi Friends, Please leave your comments as they shall be greatest motivation , shall help me make corrections to my existing posts and will enable me to create better posts. :)