# [LeetCode] Strobogrammatic 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.

Example 1:

Solution one:

Since there are not many numbers that satisfy the meaning of the question, we can use the hash table to do all the mappings that match the meaning of the question into the hash table, and then scan the double pointer to see if the two numbers in the corresponding position are hashed. There is a mapping in the table. If it does not exist, it returns false. The traversal completion returns true. See the code as follows:

Solution 2:

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

Example 1:

Input: "69" Output: trueExample 2:

Input: "88" Output: trueExample 3:

Input: "962" Output: falseThis question defines a symmetrical number, that is, a number is rotated 180 degrees as the original, that is, it is the same as the reverse, such as 609, the reverse is still 609, etc. There are actually few numbers that satisfy this condition, only 0, 1, 8, 6, 9. This question can actually be regarded as a special case of seeking the number of replies. We still use double pointers to detect, so if the first and last two numbers are equal, then only one of them is 0,1,8, if If they are not equal, one must be 6 and one is 9, or one is 9 and one is 6, and all other cases return false, see the code below;

Solution one:

Class Solution { Public : Bool isStrobogrammatic( string num) { Int l = 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 ; } };

Solution 2:

Class Solution { Public : Bool isStrobogrammatic( string num) { Unordered_map < char , char > m {{ ' 0 ' , ' 0 ' }, { ' 1 ' , ' 1 ' },

{ ' 8 ' , ' 8 ' }, { ' 6 ' , ' 9 ' }, { ' 9 ' , ' 6 ' }}; For ( int i = 0 ; i <= num.size() / 2; ++ i) { If (m[num[i]] != num[num.size() - i - 1 ]) return false ; } Return true ; } };

## No comments:

## Post a Comment