246. Strobogrammatic Number

本文介绍了一种判断数字是否为旋转对称数的方法,并提供了两种实现方案。旋转对称数是指当数字旋转180度后仍保持不变的数字,如69、88等。文章通过两个Java函数实现了这一功能。

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;
    }
}

 

转载于:https://www.cnblogs.com/joannacode/p/5965885.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值