LeetCode 246. Strobogrammatic Number

20 篇文章 0 订阅
10 篇文章 0 订阅

原题网址:https://leetcode.com/problems/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.

思路:旋转之后能够对称的数字只有0、1、6、8、9。

public class Solution {
    public boolean isStrobogrammatic(String num) {
        char[] na = num.toCharArray();
        int i=0, j=na.length-1;
        while (i<=j) {
            if ((na[i] == '0' && na[j] == '0')
            || (na[i] == '1' && na[j] == '1')
            || (na[i] == '8' && na[j] == '8')
            || (na[i] == '6' && na[j] == '9')
            || (na[i] == '9' && na[j] == '6')) {
                i ++;
                j --;
            } else {
                return false;
            }
        }
        return true;
    }
}



方法二:预先保存旋转的对应数字。

public class Solution {
    private int[] rotated = {'0', '1', (char)0x00, (char)0x00, (char)0x00, (char)0x00, '9', (char)0x00, '8', '6'};
    private boolean[] strobo = {true, true, false, false, false, false, true, false, true, true};
    public boolean isStrobogrammatic(String num) {
        char[] na = num.toCharArray();
        for(int i=0, j=na.length-1; i<(na.length+1)>>1; i++, j--) {
            if (!strobo[na[i]-'0'] || na[j] != rotated[na[i]-'0']) return false;
        }
        return true;
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值