Title: Check if a given number is Fancy Source: www.geeksforgeeks.org
A fancy number is one which when rotated 180 degrees is the same. Given a number, find whether it is fancy or not.
180 degree rotations of 6, 9, 1, 0 and 8 are 9, 6, 1, 0 and 8 respectively
Examples:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
Input: num = 96 Output: Yes If we rotate given number by 180, we get same number Input: num = 916 Output: Yes If we rotate given number by 180, we get same number Input: num = 996 Output: No Input: num = 121 Output: No |
Java solution
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 |
/* http://www.geeksforgeeks.org/check-if-a-given-number-is-fancy/ */ import java.util.Map; import java.util.HashMap; class FancyNumbers { public boolean isFancy(String num) { Map<Character, Character> fancyMap = new HashMap<>(); fancyMap.put('6', '9'); fancyMap.put('9', '6'); fancyMap.put('0', '0'); fancyMap.put('1', '1'); fancyMap.put('8', '8'); int lo = 0; int hi = num.length()-1; while(hi>=lo) { if(fancyMap.get(num.charAt(lo))==null || fancyMap.get(num.charAt(lo))!=num.charAt(hi)) { return false; } ++lo; --hi; } return true; } public static void main(String args[]) { FancyNumbers f = new FancyNumbers(); System.out.println(f.isFancy("121")); } } |