官术网_书友最值得收藏!

14. Validating ISBNs

The International Standard Book Number (ISBN) is a unique numeric identifier for books. Currently, a 13-digit format is used. However, for this problem, you are to validate the former format that used 10 digits. The last of the 10 digits is a checksum. This digit is chosen so that the sum of all the ten digits, each multiplied by its (integer) weight, descending from 10 to 1, is a multiple of 11.

The validate_isbn_10 function, shown as follows, takes an ISBN as a string, and returns true if the length of the string is 10, all ten elements are digits, and the sum of all digits multiplied by their weight (or position) is a multiple of 11:

bool validate_isbn_10(std::string_view isbn)
{
auto valid = false;
if (isbn.size() == 10 &&
std::count_if(std::begin(isbn), std::end(isbn), isdigit) == 10)
{
auto w = 10;
auto sum = std::accumulate(
std::begin(isbn), std::end(isbn), 0,
[&w](int const total, char const c) {
return total + w-- * (c - '0'); });

valid = !(sum % 11);
}
return valid;
}

You can take it as a further exercise to improve this function to also correctly validate ISBN-10 numbers that include hyphens, such as 3-16-148410-0. Also, you can write a function that validates ISBN-13 numbers.

主站蜘蛛池模板: 威信县| 静宁县| 鞍山市| 镇安县| 大悟县| 江门市| 竹溪县| 灵武市| 嘉禾县| 婺源县| 和林格尔县| 商都县| 泸水县| 宁武县| 贺州市| 淮安市| 容城县| 南康市| 绵阳市| 屏边| 晋江市| 岚皋县| 康定县| 威宁| 阳新县| 桃园市| 阳城县| 昆山市| 浠水县| 阜康市| 靖江市| 无棣县| 武汉市| 汶上县| 固始县| 老河口市| 南丹县| 五峰| 定边县| 堆龙德庆县| 阜新|