A strobogrammatic number is a number that looks the same when rotated 180 degrees (looked at upside down).
Write a function to determine if a number is strobogrammatic. The number is represented as a string.
For example, the numbers "69", "88", and "818" are all strobogrammatic.
Solution:
There are only a few characters that are valid:
6 -> 9
9 -> 6
0 -> 0 or itself
8 -> 8 or itself
1 -> 1 or itself
We can use a HashMap to record this mapping, and use two pointers to check from two sides of the string to the middle.
Code:
public class Solution { public boolean isStrobogrammatic(String num) { HashMap<Character, Character> map = new HashMap<>(); map.put('6', '9'); map.put('9', '6'); map.put('8', '8'); map.put('1', '1'); map.put('0', '0'); int i = 0; int j = num.length() - 1; while (i <= j) { if (!map.containsKey(num.charAt(i))) { return false; } if (map.get(num.charAt(i)) != num.charAt(j)) { return false; } i++; j--; } return true; } }