LintCode 644: Strobogrammatic Number

  1. Strobogrammatic Number

A mirror number is a number that looks the same when rotated 180 degrees (looked at upside down).For example, the numbers “69”, “88”, and “818” are all mirror numbers.

Write a function to determine if a number is mirror. The number is represented as a string.

Example
Example 1:

Input : “69”
Output : true
Example 2:

Input : “68”
Output : false

解法1:
注意这里跟回文数不一样,最后start==end的时候还要看该数是不是反转数。

class Solution {
public:
    /**
     * @param num: a string
     * @return: true if a number is strobogrammatic or false
     */
    bool isStrobogrammatic(string &num) {
        int n = num.size();
        int start = 0, end = n - 1;
        while(start < end) {
            if (!isUpsideDown(num[start], num[end])) return false;
            start++;
            end--;
        }
        
        return isUpsideDown(num[start], num[end]);
    }

private:
    bool isUpsideDown(char a, char b) {
        if (a == '0' && b == '0') return true;
        if (a == '1' && b == '1') return true;
        if (a == '8' && b == '8') return true;
        if (a == '6' && b == '9') return true;
        if (a == '9' && b == '6') return true;
        return false;
    }
};

解法2:网上的标准答案是用map。也不错。

/**
* This reference program is provided by @jiuzhang.com
* Copyright is reserved. Please indicate the source for forwarding
*/

class Solution {
public:
    /**
     * @param num: a string
     * @return: true if a number is strobogrammatic or false
     */
    bool isStrobogrammatic(string &num) {
        // write your code here
        map<char, char> Map;
        Map['0'] = '0';
        Map['1'] = '1';
        Map['6'] = '9';
        Map['8'] = '8';
        Map['9'] = '6';
        int i = 0;
        int j = num.size() - 1;
        while(i <= j) {
            if(Map.find(num[i]) == Map.end() || Map[num[i]] != num[j]) {
                return false;
            }
            i++;
            j--;
        }
        return true;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值