Strobogrammatic Number

https://leetcode.com/problems/strobogrammatic-number/description/

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.

For example, the numbers "69", "88", and "818" are all strobogrammatic.

Thoughts

检查一串数字是否满足翻180°还是原来的数字。 和回文一样必须两边对称,不同的是这次6和9是对称的,0, 8, 1分别和对应的相同数字对称,并且中间的数也只能是它们仨。

Code

class Solution {
public:
    bool isStrobogrammatic(string num) {
        for (int i = 0, j = num.length() - 1; i <= j; ++i, --j) {
            if (num[i] == '8' && num[j] == '8' || num[i] == '1' && num[j] == '1' || num[i] == '0' && num[j] == '0' || num[i] == '6' && num[j] == '9' || 
               num[i] == '9' && num[j] == '6')
                continue;
            return false;
        } 
        return true;
    }
};
class Solution {
    public boolean isStrobogrammatic(String num) {
        for (int l = 0, r = num.length() - 1; l <= r; l++, r--) {
            char c1 = num.charAt(l), c2 = num.charAt(r);
            if (c1 == c2 && "180".contains(c1 + "") || c1 == '6' && c2 == '9' || c1 == '9' && c2 == '6') {
                continue;
            }
            return false;
        }

        return true;
    }
}

Analysis

时间复杂度O(N)

Last updated