246. Strobogrammatic Number

Link

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.

Example 1:

Input:  "69"
Output: true

Example 2:

Input:  "88"
Output: true

Example 3:

Input:  "962"
Output: false

Solution

     public static boolean isStrobogrammatic(String num) {
        int j = num.length() - 1;
        int i = 0;
        while (j >= i) {
            if (!isStrobogrammaticChar(num.charAt(i)) || !isStrobogrammaticChar(num.charAt(i))) {
                return false;
            }
            if (num.charAt(i) == '6') {
                if (num.charAt(j) != '9') return false;
            } else if (num.charAt(i) == '9') {
                if (num.charAt(j) != '6') return false;
            }
            i++;
            j--;
        }
        return true;
    }

    private static boolean isStrobogrammaticChar(char c) {
        if (c == '2' || c == '3' || c == '4' || c == '5' || c == '7'){
            return false;
        }
        return true;
    }

Last updated

Was this helpful?