Thursday, April 14, 2016

LeetCode Q246: Strobogrammatric 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.

Solution:
The string should be sort of like palindrome.

class Solution {
public:
bool isStrobogrammatic(string num) {
for(int i=0; i<num.size(); i++)
if(num[i]!='0'&&num[i]!='1'&&num[i]!='6'&&num[i]!='8'&&num[i]!='9')
return false;
string tmp = num;
reverse(tmp.begin(), tmp.end());
for(int i=0; i<num.size(); i++){
if(tmp[i]=='6'){
tmp[i]='9';
continue;
}
if(tmp[i]=='9'){
tmp[i]='6';
continue;
}
}
for(int i=0; i<num.size(); i++){
if(num[i]!=tmp[i])
return false;
}
return true;
}
};


Round 2 solution:
class Solution {
public:
bool isStrobogrammatic(string num) {
if(num.empty())
return true;
int p0=0, p1=num.size()-1;
while(p0<=p1){
if(num[p0]!='0'&&num[p0]!='1'&&num[p0]!='6'&&num[p0]!='8'&&num[p0]!='9' &&
num[p1]!='0'&&num[p1]!='1'&&num[p1]!='6'&&num[p1]!='8'&&num[p1]!='9')
return false;
if((num[p0]=='6'&&num[p1]!='9') || (num[p0]=='9'&&num[p1]!='6'))
return false;
if(num[p0]!='6'&&num[p0]!='9'&&num[p0]!=num[p1])
return false;
p0++;
p1--;
}
return true;
}
};
view raw Q246Rnd2.cpp hosted with ❤ by GitHub

No comments:

Post a Comment