Categories:

Tags:



Problem

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

Constraints

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

Solution

The problem Strobogrammatic Number can be solved using the technique from Valid Palindrome except this time, a character rotated using a hash map is compared instead.

Implementation

class Solution
{
  public:
    bool isStrobogrammatic(string num)
    {
        unordered_map<int, int> hashmap({{'0', '0'}, {'1', '1'}, {'6', '9'}, {'8', '8'}, {'9', '6'}});
        for (int i = 0; i < num.size(); i++)
        {
            if (hashmap.find(num[i]) == hashmap.end())
                return false;
            if (hashmap[num[i]] != num[num.size() - 1 - i])
                return false;
        }

        return true;
    }
};