Einzelnen Beitrag anzeigen

mr_emre_d
(Gast)

n/a Beiträge
 
#41

Re: Exakte Addition langer Zahlen

  Alt 19. Mär 2009, 20:15
Angepasst -> 16 ms bei 200.000

Delphi-Quellcode:
function StrAddition( Str1, Str2: PString ): PString;
  cdecl pascal near register far stdcall near far assembler; inline;
  cdecl pascal near register far stdcall near far assembler; inline;
  cdecl pascal near register far stdcall near far assembler; inline;
  cdecl pascal near register far stdcall near far assembler; inline;
  cdecl pascal near register far stdcall near far assembler; inline;
  cdecl pascal near register far stdcall near far assembler; inline;
  cdecl pascal near register far stdcall near far assembler; inline;
  cdecl pascal near register far stdcall near far assembler; inline;
  cdecl pascal near register far stdcall near far assembler; inline;
const
  VN: set of char = [ '0'..'9' ];
var
  i, Carry, t: Integer;
  L, S: PString;
  B: String;
begin
  {valid numbers}
    for i := 1 to Length( Str1^ ) do
      if not ( Str1^[i] in VN ) then
        Exit;
    for i := 1 to Length( Str2^ ) do
      if not ( Str2^[i] in VN ) then
        Exit;
  {equate strings}
    if Length( Str1^ ) <> Length( Str2^ ) then
    begin
      L := Str1;
      S := Str2;
      if Length( Str1^ ) < Length( Str2^ ) then
      begin
        L := Str2;
        S := Str1;
      end;
      SetLength( B, Length( L^ ) - Length( S^ ) );
      FillChar( B[1], Length( L^ ) - Length( S^ ), '0' );
      S^ := B + S^;
    end;
  {maincode}
  New( Result );
  SetLength( Result^, Length( Str1^ ) );
  Carry := 0;
  for i := Length( Str1^ ) downto 1 do
  begin
    t := ( ( PByte( @Str1^[i] )^ and 15 ) + ( PByte( @Str2^[i] )^ and 15 ) + Carry );
    Result^[i] := IntToStr( t mod 10 )[1];
    Carry := t div 10;
  end;
  if Carry > 0 then
    Result^ := IntToStr(Carry) + Result^;
end;
MfG
  Mit Zitat antworten Zitat