原题网址:https://leetcode.com/problems/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.
For example, the numbers "69", "88", and "818" are all strobogrammatic.
思路:旋转之后能够对称的数字只有0、1、6、8、9。public class Solution {
public boolean isStrobogrammatic(String num) {
char[] na = num.toCharArray();
int i=0, j=na.length-1;
while (i<=j) {
if ((na[i] == '0' && na[j] == '0')
|| (na[i] == '1' && na[j] == '1')
|| (na[i] == '8' && na[j] == '8')
|| (na[i] == '6' && na[j] == '9')
|| (na[i] == '9' && na[j] == '6')) {
i ++;
j --;
} else {
return false;
}
}
return true;
}
}
方法二:预先保存旋转的对应数字。
public class Solution {
private int[] rotated = {'0', '1', (char)0x00, (char)0x00, (char)0x00, (char)0x00, '9', (char)0x00, '8', '6'};
private boolean[] strobo = {true, true, false, false, false, false, true, false, true, true};
public boolean isStrobogrammatic(String num) {
char[] na = num.toCharArray();
for(int i=0, j=na.length-1; i<(na.length+1)>>1; i++, j--) {
if (!strobo[na[i]-'0'] || na[j] != rotated[na[i]-'0']) return false;
}
return true;
}
}