246. Strobogrammatic Number

Posted 鱼与海洋

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了246. Strobogrammatic Number相关的知识,希望对你有一定的参考价值。

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.246. Strobogrammatic Number

 

public class Solution {
    public boolean isStrobogrammatic(String nums) {
        // 6 - > 9 , 9 - > 6 , 1 - > 1, 8 - > 8, 0 -> 0
        int array[] = {0, 1, 0, 0, 0, 0 ,9, 0, 8, 6};
        String res = "";
        for(int i = nums.length() - 1 ; i >= 0; i--){
            if(nums.charAt(i) - ‘0‘ >= 0 && nums.charAt(i) - ‘0‘ <= 9 ){
                res = res + array[nums.charAt(i) - ‘0‘] ;
            }
            else
                return false;
        }
        return res.equals(nums);
    } 
    
    //2 pointer O(n/2) ---method 2
    public boolean isStrobogrammatic(String nums) {
        int i = 0;
        int j = nums.length() - 1;
        while(i <= j){
           if(isPair(nums.charAt(i), nums.charAt(j))){
               i++;
               j--;
           }
           else return false;
        }
        return true;
    }
    public boolean isPair(char num1 , char num2){
        if(num1 == ‘6‘ && num2 == ‘9‘ ||
        num1 == ‘9‘ && num2 == ‘6‘ || 
        num1 == ‘8‘ && num2 == ‘8‘ ||
        num1 == ‘1‘ && num2 == ‘1‘||
        num1 == ‘0‘ && num2 == ‘0‘)  
            return true;
        else
            return false;
    }
}

 

以上是关于246. Strobogrammatic Number的主要内容,如果未能解决你的问题,请参考以下文章

246. Strobogrammatic Number

[LeetCode] 246. Strobogrammatic Number 对称数

java 246. Strobogrammatic Number(1st).java

java 246. Strobogrammatic Number(1st).java

java 246. Strobogrammatic Number(1st).java

java 246. Strobogrammatic Number(1st).java