228k views
5 votes
write a function called isbn check(isbn) that takes in one 13-character string of digits representing an isbn-13 number.

User Djhoese
by
7.3k points

1 Answer

7 votes

Answer:

#include <string>

#include <cstdlib>

using namespace std;

bool isbnCheck(string isbn) {

if (isbn.length() != 13) return false;

int sum = 0;

for (int i = 0; i < 13; i++) {

if (!isdigit(isbn[i])) return false;

int digit = isbn[i] - '0';

sum += (i % 2 == 0) ? digit : digit * 3;

}

return (sum % 10 == 0);

}

Step-by-step explanation:

  1. first checks if the length of the input string isbn is 13, and returns false if it is not.
  2. Then, a variable sum is initialized to keep track of the sum of the weighted digits, and a for loop is used to iterate through the digits in the ISBN number.
  3. For each digit, the isdigit function is used to check if the character is a digit, and the function returns false if it is not.
  4. The digit is then converted to an integer by subtracting the ASCII value of the character '0', and is added to the sum with a weight of 1 or 3, depending on the position of the digit.
  5. Finally, the function returns true if sum % 10 is equal to 0, which indicates a valid ISBN-13 number, and false otherwise.
User Trungly
by
8.0k points