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