Skip to content

Latest commit

 

History

History

246

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 
 
 

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

Companies:
Google, Facebook

Related Topics:
Hash Table, Math

Similar Questions:

Solution 1.

// OJ: https://leetcode.com/problems/strobogrammatic-number/
// Author: github.com/lzl124631x
// Time: O(N)
// Space: O(1)
class Solution {
private:
    bool same(char a, char b) {
        return a == b && (a == '0' || a == '1' || a == '8');
    }
    bool match(char a, char b) {
        if (a > b) swap(a, b);
        return same(a, b) || (a == '6' && b == '9');
    }
public:
    bool isStrobogrammatic(string num) {
        int i = 0, j = num.size() - 1;
        for (; i <= j; ++i, --j) {
            if ((i != j && !match(num[i], num[j]))
               || (i == j && !same(num[i], num[j]))) return false;
        }
        return true;
    }
};