Strobogrammatic Number

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

public class Solution {
     public boolean isStrobogrammatic(String num) {
        if (num == null) return false;
        if (num.isEmpty()) return true;
        if (num.contains("2") || num.contains("3") || num.contains("4") || num.contains("5") || num.contains("7")) {
            return false;
        }

        Stack<Character> stack = new Stack<>();
        for (Character character : num.toCharArray()) {
            switch (character) {
                case '0':
                    stack.push('0');
                    break;
                case '1':
                    stack.push('1');
                    break;
                case '6':
                    stack.push('9');
                    break;
                case '8':
                    stack.push('8');
                    break;
                case '9':
                    stack.push('6');
                    break;
            }
        }

        StringBuffer sb = new StringBuffer();
        while (!stack.isEmpty()) {
            sb.append(stack.pop());
        }

        return sb.toString().equals(num);
    }
}

results matching ""

    No results matching ""