- The Modern C++ Challenge
- Marius Bancila
- 212字
- 2021-06-25 22:01:25
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.
- HTML5移動Web開發技術
- Visual FoxPro程序設計教程(第3版)
- Visual C++串口通信開發入門與編程實踐
- PaaS程序設計
- 新手學Visual C# 2008程序設計
- 精通軟件性能測試與LoadRunner實戰(第2版)
- PhoneGap Mobile Application Development Cookbook
- Java項目實戰精編
- 小程序開發原理與實戰
- Getting Started with Greenplum for Big Data Analytics
- 小程序,巧應用:微信小程序開發實戰(第2版)
- Learning Ionic
- C#面向對象程序設計(第2版)
- Software Architecture with Python
- 例解Python:Python編程快速入門踐行指南