-
Notifications
You must be signed in to change notification settings - Fork 0
/
isbn.C
72 lines (60 loc) · 1.2 KB
/
isbn.C
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
#include <iostream>
#include <string>
using namespace std;
int main()
{
string input;
cin >> input;
int sum=0, cksum=0;
int Qpos = -1;
//Check if the length is 10
if(input.length() != 10)
{
cout << "INVALID INPUT" << endl;
return 0;
}
//Check if the input has valid 9 digits except the last digit.
for(int i=0;i<9;i++)
{
//Note the position of question mark.
if(input[i] == '?')
Qpos = i;
if((input[i] != '?') && (input[i] < '0' || input[i] > '9'))
{
cout << "INVALID INPUT" << endl;
return 0;
}
}
if(input[9] == '?')
Qpos = 9;
//Check if the last digit is 'X' or a digit
if((input[9] != 'X') && (input[9] < '0' || input[9] > '9'))
{
cout << "INVALID INPUT" << endl;
return 0;
}
//Compute the sum and checksum
for(int i = 0;i<10;i++)
{
if(input[i] != 'X' && input[i] != '?')
sum += (input[i] - '0')*(10-i);
else if(input[i] == 'X')
sum += 10;
}
int rem = (input[9] == 'X') ? 10 : input[9]-'0';
if(Qpos == -1 && (sum % 11) == 0)
{
cout << "ALREADY VALID" << endl;
return 0;
}
for(int i = 0;i<=9 && Qpos != -1;i++)
{
if(((10-Qpos)*i + sum)%11 == 0)
{
cout << i << endl;
return 0;
}
}
cout << "NO SOLUTION POSSIBLE" << endl;
return 0;
}