在我的代码中,如果 9 位数字之和除以 9 的余数为 10,我希望 charSum
返回 'X'
。我尝试了两个 charSum = 'X'
和 charSum = (char) 88
都不起作用。我的算法中一定有什么地方错了。请帮忙。
public static char getCheckSum(String isbn) {
int sum = 0;
for (int i = 0; i < isbn.length(); i++) {
int[] num = new int[isbn.length()];
num[i] = Character.getNumericValue(isbn.charAt(i));
sum = sum + num[i];
}
int last = (sum % 11);
char charSum;
if (last == 10){
charSum = 'X';
} else {
charSum = (char) (last + 48);
}
return charSum;
}
public static String formatISBNWithHyphens(String isbn) {
// original isbn: 123456789
// possible new isbn: 1-234-56789-X
char isbn10 = getCheckSum(isbn);
String isbn10Str = isbn + Character.toString(isbn10);
// char[] c = new char[isbn10Str.length()]; *leaving this here for future learning.
String[] cStr = new String[isbn10Str.length()];
String isbnStr = "";
for (int i = 0; i < isbn10Str.length(); i++){
cStr[i] = Character.toString(isbn10Str.charAt(i));
// c[i] = isbn10Str.charAt(i); *leaving this here for future learning.
if (i == 0 || i == 3 || i == 8 ) {
cStr[i] += '-';
}
isbnStr += cStr[i];
}
return isbnStr;
}
最佳答案
它工作正常。如果我用 933456789
运行它(总和为 54,所以 54 % 11 = 10),getCheckSum()
方法返回 X
正如预期的那样。
但是,这似乎不是计算 ISBN-10 校验和的正确方法。根据 Wikipedia :
The 2001 edition of the official manual of the International ISBN Agency says that the ISBN-10 check digit – which is the last digit of the ten-digit ISBN – must range from 0 to 10 (the symbol X is used for 10), and must be such that the sum of all the ten digits, each multiplied by its (integer) weight, descending from 10 to 1, is a multiple of 11.
我按照规范实现了如下:
public static char getCheckDigit(String isbn) {
if (isbn == null || !isbn.matches("[0-9]{9,}")) {
throw new IllegalArgumentException("Illegal ISBN value");
}
int sum = 0;
for (int i = 0; i < 9; i++) {
sum += ((10 - i) * Character.digit(isbn.charAt(i), 10));
}
int check = ((11 - (sum % 11)) % 11);
return check == 10 ? 'X' : Character.forDigit(check, 10);
}
应用于我在同一个维基百科页面上找到的几个 ISBN 值:
getCheckDigit("097522980"); // --> returns 'X'
getCheckDigit("094339604"); // --> returns '2'
getCheckDigit("999215810"); // --> returns '7'
关于java - 9位除以11的和为10时返回 'X',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31846240/