mirror of
https://codeberg.org/andyscott/exercism.git
synced 2024-11-14 15:20:48 -05:00
30 lines
615 B
Zig
30 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;
|
||
|
}
|