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.
益智题,能自我旋转的有0,1,8,能在侧翼旋转的有6,9。用hashmap判断左右对称的值是不是要找的值即可。代码如下:
public class Solution {
public boolean isStrobogrammatic(String num) {
HashMap<Character, Character> hs = new HashMap<Character, Character>();
hs.put('0', '0');
hs.put('1', '1');
hs.put('6', '9');
hs.put('8', '8');
hs.put('9', '6');
for (int i = 0; i <= num.length() >> 1; i++) {
if (!hs.containsKey(num.charAt(i))) {
return false;
} else {
if (hs.get(num.charAt(i)) != (num.charAt(num.length() - 1 - i))) {
return false;
}
}
}
return true;
}
}
这题比较取巧的方法是下面这个:
public boolean isStrobogrammatic(String num) {
for (int i=0, j=num.length()-1; i <= j; i++, j--)
if (!"00 11 88 696".contains(num.charAt(i) + "" + num.charAt(j)))
return false;
return true;
}
做着自己都承认比较取巧……