Skip to content

246. Strobogrammatic Number 👎

  • Time: $O(n)$
  • Space: $O(10) = O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
class Solution {
 public:
  bool isStrobogrammatic(string num) {
    const vector<char> rotated{'0', '1', 'x', 'x', 'x',
                               'x', '9', 'x', '8', '6'};
    int l = 0;
    int r = num.length() - 1;

    while (l <= r)
      if (num[l++] != rotated[num[r--] - '0'])
        return false;

    return true;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
class Solution {
  public boolean isStrobogrammatic(String num) {
    final char[] rotated = {'0', '1', 'x', 'x', 'x', 'x', '9', 'x', '8', '6'};
    int l = 0;
    int r = num.length() - 1;

    while (l <= r)
      if (num.charAt(l++) != rotated[num.charAt(r--) - '0'])
        return false;

    return true;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
class Solution:
  def isStrobogrammatic(self, num: str) -> bool:
    rotated = {'0': '0', '1': '1', '6': '9', '8': '8', '9': '6'}
    l = 0
    r = len(num) - 1

    while l <= r:
      if num[r] not in rotated:
        return False
      if num[l] != rotated[num[r]]:
        return False
      l += 1
      r -= 1

    return True