246. Strobogrammatic Number
Easy
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:
Input: num = "69" Output: true
Example 2:
Input: num = "88" Output: true
Example 3:
Input: num = "962" Output: false
Example 4:
Input: num = "1" Output: true
//Java class Solution { Map<Character, Character> map = new HashMap<>(); public boolean isStrobogrammatic(String num) { map.put('0', '0'); map.put('1', '1'); map.put('6', '9'); map.put('8', '8'); map.put('9', '6'); StringBuilder ret = new StringBuilder(); for(int i=num.length()-1; i>=0; --i){ char c = num.charAt(i); if(!map.containsKey(c)) return false; ret.append(map.get(c)); } return ret.toString().equals(num.toString()); } } //C++ //C++: 0ms class Solution { public: bool isStrobogrammatic(string num) { int n = num.size(), l = 0, r = n-1; while(l<=r){ if(num[l]==num[r] && num[l]!='0' && num[l]!='1' && num[l]!='8') return false; if(num[l]!=num[r] && !((num[l]=='6'&&num[r]=='9')||(num[l]=='9'&&num[r]=='6'))) return false; l++; r--; } return true; } };
No comments:
Post a Comment