2

ISBN-13の規則に従って、読み取っている文字列 (文字列であることが重要) が正しいかどうかを確認しようとしています 。式を見つけた

たとえば、ISBN-13 チェック ディジットの 978-0-306-40615-?

は次のように計算されます。

s = 9×1 + 7×3 + 8×1 + 0×3 + 3×1 + 0×3 + 6×1 + 4×3 + 0×1 + 6×3 + 1×1 + 5×3
  =   9 +  21 +   8 +   0 +   3 +   0 +   6 +  12 +   0 +  18 +   1 +  15
  = 93
93 / 10 = 9 remainder 3
10 –  3 = 7`

私の問題は、1 つの数値を 1 で乗算し、他のすべての数値を 3 で乗算する方法がわからないことです。forループを推測していますが、開始方法がわかりません。

4

5 に答える 5

5

正規表現を「単純に」使用できます。

ISBN(-1(?:(0)|3))?:?\x20+(?(1)(?(2)(?:(?=.{13}$)\d{1,5}([ -])\d{1,7}\3\d{1,6}\3(?:\d|x)$)|(?:(?=.{17}$)97(?:8|9)([ -])\d{1,5}\4\d{1,7}\4\d{1,6}\4\d$))|(?(.{13}$)(?:\d{1,5}([ -])\d{1,7}\5\d{1,6}\5(?:\d|x)$)|(?:(?=.{17}$)97(?:8|9)([ -])\d{1,5}\6\d{1,7}\6\d{1,6}\6\d$)))

于 2011-11-03T12:09:32.813 に答える
4

(偶数、奇数) の数のペアが 6 つあるので、それらをペアで調べます。

    for (i = 0; i < 6; i++) {
    even += array[2*i];
    odd += array[2*i+1]*3;
    }
    checkbit = 10 - (even+odd)%10;
于 2011-11-03T12:16:37.353 に答える
1

あなたのinputStringがasciiであると仮定します:

    int odd = 0;
    int even = 0;
    char[] c = (inputString + "00").replaceAll("[\\-]", "").toCharArray();
    for (int i = 0; i < (c.length - 1) / 2; ++i) {
        odd += c[2 * i] - 48;
        even += c[2 * i + 1] - 48;
    }
    int result = 10 - (odd + 3 * even) % 10;
于 2011-11-03T12:50:06.420 に答える
1

これは効果的に機能しているようで、明確です。

// Calculates the isbn13 check digit for the 1st 12 digits in the string.
private char isbn13CheckDigit(String str) {
  // Sum of the 12 digits.
  int sum = 0;
  // Digits counted.
  int digits = 0;
  // Start multiplier at 1. Alternates between 1 and 3.
  int multiplier = 1;
  // Treat just the 1st 12 digits of the string.
  for (int i = 0; i < str.length() && digits < 12; i++) {
    // Pull out that character.
    char c = str.charAt(i);
    // Is it a digit?
    if ('0' <= c && c <= '9') {
      // Keep the sum.
      sum += multiplier * (c - '0');
      // Flip multiplier between 1 and 3 by flipping the 2^1 bit.
      multiplier ^= 2;
      // Count the digits.
      digits += 1;
    }
  }
  // What is the check digit?
  int checkDigit = (10 - (sum % 10)) % 10;
  // Give it back to them in character form.
  return (char) (checkDigit + '0');
}

注意: 0 のチェック ディジットを正しく処理するように編集しました。チェック ディジットが 0 の isbn の例については、 Wikipedia International Standard Book Numberを参照してください。

ポール

于 2011-11-03T15:17:52.007 に答える
0

同様に、ループとひどい文字から文字列への変換があります;]

boolean isISBN13(String s){
    String ss = s.replaceAll("[^\\d]", "");
    if(ss.length()!=13)
        return false;
    int sum=0, multi=1;
    for(int i=0; i<ss.length()-1; ++i){
        sum += multi * Integer.parseInt(String.valueOf(ss.charAt(i)));
        multi = (multi+2)%4; //1 or 3
    }
    return (Integer.parseInt(String.valueOf(ss.charAt(ss.length()))) == (10 - sum%10));
}
于 2011-11-03T12:36:48.843 に答える