# Not sure loop-switch is an anti-pattern or not (0ms C++)

• https://en.wikipedia.org/wiki/Loop-switch_sequence

Wiki said we should avoid loop-switch, should we?

``````class Solution {
public:
bool isStrobogrammatic(string num) {
if(num.empty()) return true; // fixit
int len = (int)num.size();
for(int i=0; i<=len/2; i++) {
switch (num[i]) {
case '1':
case '8':
case '0': if(num[i]==num[len-1-i]) continue; else return false;
case '6': if(num[len-1-i]=='9') continue; else return false;
case '9': if(num[len-1-i]=='6') continue; else return false;
default: return false;
}
}
return true;
}
};``````

• Yes, we should avoid loop-switch. It makes code unreadable and difficult to maintain. As shown below I refactored the switch case logic to a private function and it looks more readable. BTW your code may get exception if the string is empty, since it attempts to access the num[0] which does not exist.

``````class Solution {
public:
bool isStrobogrammatic(string num) {
int i = 0, j = num.size() - 1;

while (i < j && IsCharsStrobogrammatic(num[i], num[j])) {
i++;
j--;
}

// an empty string will be considered as being strobogrammatic
return i >= j;
}

private:
bool IsCharsStrobogrammatic(char x, char y) {
return (x == '1' || x == '8' || x == '0') && x == y ||
(x == '6' && y == '9') || (x == '9' && y == '6');
}

};
``````

• Thank you for your explanation :)

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.