exercism/zig/luhn/luhn.zig
2024-11-02 17:31:53 -04:00

29 lines
615 B
Zig

const std = @import("std");
const ascii = std.ascii;
pub fn isValid(s: []const u8) bool {
var idx: usize = s.len;
var luhn_idx: usize = 1;
var total: u64 = 0;
while (idx > 0) {
idx -= 1;
if (s[idx] == 32) continue;
if (!ascii.isDigit(s[idx])) {
return false;
}
var curr: u8 = s[idx] - 48;
if (luhn_idx % 2 == 0) {
curr *= 2;
if (curr > 9) {
curr -= 9;
}
}
total += curr;
luhn_idx += 1;
}
if (luhn_idx <= 2) return false;
return total % 10 == 0;
}