试题编号: 201312-2
试题名称: ISBN号码
时间限制: 1.0s
内存限制: 256.0MB
问题描述:
问题描述
每一本正式出版的图书都有一个ISBN号码与之对应,ISBN码包括9位数字、1位识别码和3位分隔符,其规定格式如“x-xxx-xxxxx-x”,其中符号“-”是分隔符(键盘上的减号),最后一位是识别码,例如0-670-82162-4就是一个标准的ISBN码。ISBN码的首位数字表示书籍的出版语言,例如0代表英语;第一个分隔符“-”之后的三位数字代表出版社,例如670代表维京出版社;第二个分隔之后的五位数字代表该书在出版社的编号;最后一位为识别码。
识别码的计算方法如下:
首位数字乘以1加上次位数字乘以2……以此类推,用所得的结果mod 11,所得的余数即为识别码,如果余数为10,则识别码为大写字母X。例如ISBN号码0-670-82162-4中的识别码4是这样得到的:对067082162这9个数字,从左至右,分别乘以1,2,…,9,再求和,即0×1+6×2+……+2×9=158,然后取158 mod 11的结果4作为识别码。
编写程序判断输入的ISBN号码中识别码是否正确,如果正确,则仅输出“Right”;如果错误,则输出是正确的ISBN号码。
输入格式
输入只有一行,是一个字符序列,表示一本书的ISBN号码(保证输入符合ISBN号码的格式要求)。
输出格式
输出一行,假如输入的ISBN号码的识别码正确,那么输出“Right”,否则,按照规定的格式,输出正确的ISBN号码(包括分隔符“-”)。
样例输入
0-670-82162-4
样例输出
Right
样例输入
0-670-82162-0
样例输出
0-670-82162-4
题目解析:就是简单的获取字符计算值,不过一种可以使用截取,一种可以使用循环。在计算过程中可以有多种实现形式。
代码:
#include<stdio.h>
#include<math.h>
#include<algorithm>
#include<string.h>
#include<iostream>
#include<iomanip>
#include<vector>
#include<map>
#include<set>
#include<stack>
#include<queue>
using namespace std;
int main()
{
string str;
while(cin >> str){
int index; //查找的下标
int begin = 0; //截取字符串的开始地址
string temp; //除识别码外所有字符组合在一起
while((index = str.find("-",index)) != string::npos){
temp += str.substr(begin,index - begin);
begin = index + 1;
index++;
}
int sum = 0; //计算值
for(int i = 0; i < temp.size(); i++){
sum += (temp[i] - '0') * (i+1);
}
string shibiema = str.substr(begin,str.size() - begin); //截取识别码
int rst = sum % 11; //计算余数
string fuhao; //将余数转换为字符形式
if(rst == 10){ //最大是10
fuhao = "X";
}else{
fuhao = char(rst + '0');
}
string rightrst = str.substr(0,str.size() - 1); //将源字符串除了识别码都截取
rightrst += fuhao; //和真正识别码组合成为正确识别码
if(fuhao == shibiema){ //比较计算结果和识别码
cout << "Right" << endl;
}else{
cout << rightrst << endl;
}
}
return 0;
}
/* 另一种,不截取字符,直接计算,最后用replace替换字符
#include<stdio.h>
#include<math.h>
#include<algorithm>
#include<string.h>
#include<iostream>
#include<iomanip>
#include<vector>
#include<map>
#include<set>
#include<stack>
#include<queue>
using namespace std;
int main()
{
string str,rst;
while(cin >> str){
int sum = 0;
int count = 1;
for(int i = 0; i < str.size() - 1;i++){
if(str[i] != '-'){
sum += (str[i] - '0') * count;
count++;
}
}
int a = sum % 11;
if(a == 10){
rst = "X";
}else{
rst = char(a + '0');
}
string shibiefu = str.substr(12,1);
if(rst == shibiefu){
cout << "Right" << endl;
}else{
str.replace(12,1,rst);
cout << str << endl;
}
}
return 0;
}
*/
1560

被折叠的 条评论
为什么被折叠?



