246. 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.

Example 1:

Input:
  "69"

Output:
 true

Example 2:

Input:
  "88"

Output:
 true

Example 3:

Input:
  "962"

Output:
 false

Solution

(1) Java

class Solution {
    public boolean isStrobogrammatic(String num) {
        Set<Character> set = new 
            HashSet<>(Arrays.asList('0','1','8'));
        char[] chars = num.toCharArray();
        int i = 0; 
        int j = chars.length-1;
        while (i <= j) {
            if (chars[i] == chars[j] && set.contains(chars[i])) {
                i++;
                j--;
                continue;
            } else if ((chars[i] == '6' && chars[j] == '9') ||
                       (chars[i] == '9' && chars[j] == '6'))
            {
                i++;
                j--;
                continue;
            }
            return false;
        }
        return true;
    }
}

More concise code

public boolean isStrobogrammatic(String num) {
    for (int i=0, j=num.length()-1; i <= j; i++, j--)
        if (!"00 11 88 696".contains(num.charAt(i) + "" + num.charAt(j)))
            return false;
    return true;
}

(2) Python



(3) Scala



results matching ""

    No results matching ""