Each officially published book has a corresponding ISBN. An ISBN consists of 9 digits, 1 identification code, and 3 separators, with the specified format being "x-xxx-xxxxx-x". The symbol "-" is the separator (the minus sign on the keyboard), and the last digit is the identification code. For example, 0-670-82162-4 is a standard ISBN code. The first digit of the ISBN represents the language of publication, with 0 representing English; the three digits after the first separator "-" represent the publisher, with 670 representing Viking Publishing House; the five digits after the second separator represent the book's number at the publisher; and the last digit is the identification code.
The calculation method for the identification code is as follows: Multiply the first digit by 1, add the second digit multiplied by 2, and so on. Then, take the result mod 11. The remainder is the identification code. If the remainder is 10, the identification code is the uppercase letter X.
For example, in the ISBN 0-670-82162-4, the identification code 4 is calculated as follows: For the 9 digits 067082162, from left to right, multiply each digit by 1, 2, ..., 9 respectively, then sum them up. That is, 0 × 1 + 6 × 2 + ... + 2 × 9 = 158. Then, take the result of 158 mod 11, which is 4, as the identification code.
Your task is to write a program to determine whether the identification code in the input ISBN is correct. If it is correct, output only "Right." If it is incorrect, output what you believe is the correct ISBN.
Sample Inputs/Outputs
Sample Input(s) | Sample Output(s) |
---|---|
EOF inputs: each line contains a character sequence representing an ISBN for a book (the input is guaranteed to meet the formatting requirements of an ISBN). | If the identification code of the input ISBN is correct, output "Right". Otherwise, output the correct ISBN according to the specified format (including the separator "-"). |
0-670-82162-4 0-670-82162-0 | Right 0-670-82162-4 |
Thought Process
Use a For loop to exclude the hyphens and determine the identification code. If the identification code matches the last character of the string, output "Right". If they don't match, replace the last character of the string with the correct identification code and output the string.
Sample Code-ZeroJudge D103: ISBN Number
#include <iostream>
using namespace std;
int main() {
string str;
while (cin >> str)
{
string num = "";
int sum = 0;
string output = "";
for (int i = 0; i<str.length()-1; i++)
{
if (str[i] != '-') num += str[i];
output += str[i];
}
for (int i = 0; i<num.length(); i++)
{
sum += int(num[i] - '0') * (i+1);
}
string ans;
if (sum % 11 < 10) ans = to_string(sum % 11);
else ans = "X";
if (ans[0] == str[str.length()-1]) cout << "Right\n";
else cout << output << ans << "\n";
}
}
//ZeroJudge D103
//Dr. SeanXD