Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <vector>
- using namespace std;
- int findMissingISBN(string isbn){
- vector<int> digits;
- bool foundMissing = false;
- int sum = 0, missingPosition = -1, result, cntDashes = 0;
- for(int i = 0; i < isbn.length(); i++){
- if(isbn.at(i) == '-' && !foundMissing){
- cntDashes++;
- }
- if(isbn.at(i) == '?'){
- missingPosition = i;
- foundMissing = true;
- digits.push_back(0);
- continue;
- }
- if(isbn.at(i) != '-' && (isbn.at(i) != 'X' || isbn.at(i) != 'x')){
- digits.push_back((int)(isbn.at(i) - 48));
- }
- if(isbn.at(i) == 'X' || isbn.at(i) == 'x'){
- digits.push_back(10);
- }
- }
- for(int i = 0; i < digits.size(); i++){
- sum += ((digits.at(i) * (i + 1)) % 11);
- }
- missingPosition -= cntDashes - 1;
- if(missingPosition < 0){
- throw invalid_argument("The missing digit must be marked as \"?\"!");
- } else {
- for(int i = 1; i <= 11; i++){
- int curr = sum + (missingPosition * i);
- if(curr % 11 == 0){
- return i;
- }
- }
- }
- }
- int main() {
- // must put ? on the missing element
- // 0-19-85?803-0
- // and the element is 3
- string isbn;
- cin >> isbn;
- cout << findMissingISBN(isbn);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement