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

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.

主站蜘蛛池模板: 泽普县| 普定县| 大名县| 瑞丽市| 莆田市| 阿图什市| 龙川县| 盱眙县| 扶绥县| 房产| 阿尔山市| 洪泽县| 原平市| 阜宁县| 兴化市| 阳曲县| 宁远县| 江达县| 祥云县| 三亚市| 中方县| 灌南县| 邛崃市| 肥西县| 崇明县| 佛冈县| 扬州市| 永修县| 江达县| 德江县| 新宾| 四子王旗| 融水| 镇远县| 綦江县| 云霄县| 密云县| 汉川市| 朔州市| 汕头市| 阿城市|