您的位置:首页 > 其它

LeetCode 246. Strobogrammatic Number

2016-04-07 06:08 393 查看
原题网址: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;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: