function isBinary(s: string): boolean {
const binary: RegExp = /^[01]+$/;
return binary.test(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
*/
function divisibleBy7(s: string): boolean {
let remainder = 0;
for (const c of s) {
remainder = (remainder * 2 + (c.charCodeAt(0) - '0'.charCodeAt(0))) % 7;
}
return remainder === 0;
}
// Equivalent of main()
const s = "00011100"; // 28
if (!isBinary(s)) {
console.log("Not a binary string");
} else {
if (divisibleBy7(s)) {
console.log("Divisible by 7");
} else {
console.log("Not divisible by 7");
}
}
/*
run:
"Divisible by 7"
*/