Skip to content

246. Strobogrammatic Number

Given a string num which represents an integer, return true if num is a strobogrammatic number**.

A strobogrammatic number is a number that looks the same when rotated 180 degrees (looked at upside down).

Example 1:

Input: num = "69"
Output: true

Example 2:

Input: num = "88"
Output: true

Example 3:

Input: num = "962"
Output: false

Constraints:

  • 1 <= num.length <= 50
  • num consists of only digits.
  • num does not contain any leading zeros except for zero itself.

Solution:

class Solution {
    public boolean isStrobogrammatic(String num) {
            // 1 2 3 4 5 6 7 8 9 
        if (num.length() == 1){
            if (num.charAt(0) == '1' || num.charAt(0) == '8' || num.charAt(0) == '0'){
                return true;
            }else{
                return false;
            }
        }
        int left = 0;
        int right = num.length() - 1;


        while(left < right){
            if (num.charAt(left) == '1' && num.charAt(right) == '1'){
                left++;
                right--;
            }else if (num.charAt(left) == '9' && num.charAt(right) == '6'){
                left++;
                right--;
            }else if (num.charAt(left) == '6' && num.charAt(right) == '9'){
                left++;
                right--;
            }else if (num.charAt(left) == '8' && num.charAt(right) == '8'){
                left++;
                right--;
            }else if (num.charAt(left) == '0' && num.charAt(right) == '0'){
                left++;
                right--;
            }else{
                return false;
            }
        }

        if (left == right){
            if (num.charAt(left) == '1' || num.charAt(left) == '8' || num.charAt(left) == '0'){
                return true;
            }else{
                return false;
            }
        }

        return true;

    }
}
// TC: O(n)
// SC: O(1)
class Solution {
    public boolean isStrobogrammatic(String num) {
        Map<Character, Character> rotatedDigits = new HashMap<>(
            Map.of('0', '0', '1', '1', '6', '9', '8', '8', '9', '6')
        );

        StringBuilder rotatedStringBuilder = new StringBuilder();

        for (int i = num.length() - 1; i>= 0; i--){
            char c = num.charAt(i);
            if(!rotatedDigits.containsKey(c)){
                return false;
            }

            rotatedStringBuilder.append(rotatedDigits.get(c));
        }

        String rotatedString = rotatedStringBuilder.toString();
        return num.equals(rotatedString);


    }
}