use regex::Regex;
fn is_binary(s: &str) -> bool {
let binary = Regex::new(r"^[01]+$").unwrap();
binary.is_match(s)
}
/*
In decimal: reading "123" means
remainder = remainder * 10 + digit
In binary: reading "1011" means
remainder = remainder * 2 + bit
*/
/*
0 (0*2 + 0) % 7 0
0 (0*2 + 0) % 7 0
0 (0*2 + 0) % 7 0
1 (0*2 + 1) % 7 1
1 (1*2 + 1) % 7 3
1 (3*2 + 1) % 7 0
0 (0*2 + 0) % 7 0
0 (0*2 + 0) % 7 0
*/
fn divisible_by_7(s: &str) -> bool {
let mut remainder = 0;
for c in s.chars() {
remainder = (remainder * 2 + (c as i32 - '0' as i32)) % 7;
}
remainder == 0
}
fn main() {
let s = "00011100"; // 28
if !is_binary(s) {
println!("Not a binary string");
return;
}
if divisible_by_7(s) {
println!("Divisible by 7");
} else {
println!("Not divisible by 7");
}
}
/*
run:
Divisible by 7
*/