1 条题解
-
0
【例40.3】ISBN码
解题思路
扫描末位前的字符,跳过连字符,将9个数字依次乘1~9求和,模11得到校验值;10映射X。比较末位,正确输出Right,错误仅替换末位。
正确性说明
计算规则直接来自题目定义。按所述顺序处理时,已完成部分的结果被准确保存在累加量、计数或当前状态中;下一步只加入新增贡献。最终得到完整要求的结果。
易错点
权重只随数字增加,不随分隔符增加;保留原格式。
复杂度
串长固定,时间O(1),空间O(1)。
参考代码(C++11)
#include <bits/stdc++.h> using namespace std; int main() { ios::sync_with_stdio(false); cin.tie(nullptr); string s; cin >> s; int sum = 0, w = 1; for (size_t i = 0; i + 1 < s.size(); i++) if (s[i] != '-') sum += (s[i] - '0') * w++; int r = sum % 11; char c = r == 10 ? 'X' : char('0' + r); if (s.back() == c) cout << "Right"; else { s.back() = c; cout << s; } cout << "\n"; return 0; }
- 1