题目:
解法一:
boolean isbnVerifier(String stringToVerify) {
int sum = 0;String numbers = stringToVerify.replaceAll("[^0-9X]","").toString();if (numbers.length() != 10 ) {
throw new IllegalArgumentException("Invalid Argument");}int[] output = convertStringToNumbers(numbers);for (int i = 0; i < numbers.length(); i++) {
sum += (10 - i) * output[i];}return sum % 11 == 0;}int[] convertStringToNumbers(String s) {
int[] output = new int[10];char[] sets = {
'0','1','2','3','4','5','6','7','8','9',};for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == 'A') {
output[i] = 10;}for (int j = 0; j < 10; j++) {
if (s.charAt(i) == sets[j]) {
output[i] = j;}}}return output;}
解法二:
/*** 解法二*/boolean isValid(String stringToVerify) {
char[] chars = stringToVerify.replaceAll("[^0-9X]","").toCharArray();if (chars.length != 10) {
throw new IllegalArgumentException("Invalid Argument");}int sum = 0;int subSum = 0;for (int i = 0; i < chars.length; i++) {
subSum = chars[i] == 'X' ? 10 : (10 - i) * Character.getNumericValue(chars[i]);}return sum % 11 == 0;}
Conclusion:
由于不知道Character类有检测char是否为数字的方法,自己造了个轮子。推荐方法二,简明扼要,beautiful code!