exercism/zig/isbn-verifier/isbn_verifier.zig

40 lines
910 B
Zig

const std = @import("std");
pub fn isValidIsbn10(s: []const u8) bool {
if (s.len < 10) return false;
var isbn: [10]u8 = undefined;
var pos: usize = 0;
for (s) |c| {
if (pos == 10) return false;
isbn[pos] = switch (c) {
'-' => continue,
'0'...'9' => blk: {
pos += 1;
break :blk std.fmt.parseInt(u8, &[_]u8{c}, 10) catch unreachable;
},
else => blk: {
if (c == 'X' and pos == 9) {
pos += 1;
break :blk 10;
} else {
return false;
}
},
};
}
var sum: u32 = 0;
var factor: usize = 10;
var i: usize = 0;
while (factor > 0) : ({
factor -= 1;
i += 1;
}) {
sum += @intCast(isbn[i] * factor);
}
return sum % 11 == 0;
}