Advertisement
Guest User

Untitled

a guest
Nov 18th, 2017
61
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.40 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3.  
  4. using namespace std;
  5.  
  6. int findMissingISBN(string isbn){
  7.     vector<int> digits;
  8.     bool foundMissing = false;
  9.     int sum = 0, missingPosition = -1, result, cntDashes = 0;
  10.  
  11.     for(int i = 0; i < isbn.length(); i++){
  12.         if(isbn.at(i) == '-' && !foundMissing){
  13.             cntDashes++;
  14.         }
  15.         if(isbn.at(i) == '?'){
  16.             missingPosition = i;
  17.             foundMissing = true;
  18.             digits.push_back(0);
  19.             continue;
  20.         }
  21.         if(isbn.at(i) != '-' && (isbn.at(i) != 'X' || isbn.at(i) != 'x')){
  22.             digits.push_back((int)(isbn.at(i) - 48));
  23.         }
  24.         if(isbn.at(i) == 'X' || isbn.at(i) == 'x'){
  25.             digits.push_back(10);
  26.         }
  27.     }
  28.  
  29.     for(int i = 0; i < digits.size(); i++){
  30.         sum += ((digits.at(i) * (i + 1)) % 11);
  31.     }
  32.  
  33.     missingPosition -= cntDashes - 1;
  34.  
  35.     if(missingPosition < 0){
  36.         throw invalid_argument("The missing digit must be marked as \"?\"!");
  37.     } else {
  38.         for(int i = 1; i <= 11; i++){
  39.             int curr = sum + (missingPosition * i);
  40.             if(curr % 11 == 0){
  41.                 return i;
  42.             }
  43.         }
  44.     }
  45. }
  46.  
  47. int main() {
  48.     // must put ? on the missing element
  49.     // 0-19-85?803-0
  50.     // and the element is 3
  51.     string isbn;
  52.     cin >> isbn;
  53.     cout << findMissingISBN(isbn);
  54.    
  55.     return 0;
  56. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement