A strobogrammatic number is a number this looks the same when rotated-degrees (looked at upside).
Write a function to determine if a number is strobogrammatic. The number is represented as a string.
For example, the numbers "", "" "," "and" 818 "is all strobogrammatic.
This problem defines a symmetric number, that is, a number rotation 180 degrees and the original, that is, the opposite look, such as 609, upside down or 609 and so on, to meet this condition of the number actually few, only 0,1,8,6,9. This problem can be seen as a special case of palindrome number, we still use a double pointer to detect, then the first and last two numbers if equal, then only they are the middle of the 0,1,8, if they are not equal, must be 61 is 9, or one is 91 is 6, All other cases return false, see code below;
Solution One:
classSolution { Public: BOOLIsstrobogrammatic (stringnum) { intL =0, r = num.size ()-1; while(L <=r) {if(Num[l] = =Num[r]) { if(Num[l]! ='1'&& Num[l]! ='0'&& Num[l]! ='8'){ return false; } } Else { if((num[l]! ='6'|| NUM[R]! ='9') && (num[l]! ='9'|| NUM[R]! ='6')) { return false; } } ++l; --R; } return true; }};
Because the number of satisfied test instructions is not many, so we can use a hash table to do, all the mappings that conform to test instructions into the Hashtable, and then double-pointer scan to see if the corresponding position of the two numbers in the hash tables exist mappings, if not present, return false, the completion of the traversal to return true, see the code as follows:
Solution Two:
classSolution { Public: BOOLIsstrobogrammatic (stringnum) {Unordered_map<Char,Char> m {{'0','0'}, {'1','1'}, {'8','8'}, {'6','9'}, {'9','6'}}; for(inti =0; I <= num.size ()/2; ++i) {if(M[num[i]]! = num[num.size ()-I-1])return false; } return true; }};
Similar topics:
Resources:
Https://leetcode.com/discuss/72921/5-lines-concise-and-easy-understand-c-solution
Leetcode all in one topic summary (continuous update ...)
[Leetcode] Strobogrammatic number symmetry