How to check if a string contains only 0 and 1 and is divisible by 7 in Pascal

1 Answer

0 votes
program BinaryDivisibleBy7;

{$mode objfpc}  { enables modern Pascal features }

{ Check if a string contains only '0' and '1' }
function IsBinary(const s: string): Boolean;
var
  i: Integer;
begin
  if s = '' then
    Exit(False);

  for i := 1 to Length(s) do
    if not (s[i] in ['0', '1']) then
      Exit(False);

  Result := True;
end;

{
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
}

{ Compute binary string modulo 7 without overflow }
function DivisibleBy7(const s: string): Boolean;
var
  i: Integer;
  remainder: Integer;
begin
  remainder := 0;

  for i := 1 to Length(s) do
  begin
    remainder := (remainder * 2 + (Ord(s[i]) - Ord('0'))) mod 7;
  end;

  Result := (remainder = 0);
end;

var
  s: string;

begin
  s := '00011100';  { 28 }

  if not IsBinary(s) then
  begin
    Writeln('Not a binary string');
    Halt;
  end;

  if DivisibleBy7(s) then
    Writeln('Divisible by 7')
  else
    Writeln('Not divisible by 7');
end.




(*
run:

Divisible by 7

*)

 



answered Mar 1 by avibootz

Related questions

...