[leetcode 246] Strobogrammatic Number

来源:互联网 发布:比特币 软件 编辑:程序博客网 时间:2024/05/22 17:21

Question:

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.


Hide Tags Hash Table Math 

Hide Similar Problems (M) Strobogrammatic Number II (H) Strobogrammatic Number III.


分析:

Strobogrammatic Number 就是一个数字翻转180度后仍为原数据的数。比如,181、69翻转180度后都仍为原数据。

基本的Strobogrammatic Number 为:0、1、8、6和9。

其中0、1、8是自身对称,所以这三个数,要么只出现在中间位置,要么出现在对称位置,比如181,10801;

其中6和9是互为颠倒对称,6和9只能同时出现在对称位置,比如619,6969。


所以判断一个数据是否为 Strobogrammatic Number 则只要判断其对称位置是否为基本的Strobogrammatic Number即可。


代码如下:

public class Solution {
    public boolean isStrobogrammatic(string num) {
        // 0, 1, 69, 8
int len = num.length();
        if (len == 0) {
            return false;
        }
        
        int left = 0;         
int right = len - 1;
        while (left <= right) {
            char l = num[left];
            char r = num.[right];
            if (l == r) {
              if (l != '8' && l != '1' && l != '0') {
                    return false;
              } 
}
else {
               if (!(l == '6' && r == '9') && !(l == '9' && r == '6')) {
                        return false;
                } 
            }
           left++;
           right--; 
        }
        return true;
}
};

0 0