: はここに私のコードオフの例です。
最初に長さを比較し、同じ場合は、左から右の文字を比較すると良い戦略になります。
NB。文字列の末尾に空白や先頭の空白が含まれている場合は、それを削除してから比較してください。ここで
(デルファイとFreePascalとで動作するはずです)昇順に(文字列として)の値をソートするSTRINGLISTを使った例です:
program ProjTestBigIntSort;
{$APPTYPE CONSOLE}
uses
Classes;
type
TMyStringList = class(TStringList)
protected
function CompareStrings(const S1, S2: string): Integer; override;
end;
function TMyStringList.CompareStrings(const S1, S2: string): Integer;
var
i : Integer;
begin
// Trimming leading/trailing spaces and leading zeroes might be needed first
Result := 0;
// Compare length, shortest sorts first
if (Length(S1) > Length(S2)) then begin
Result := 1;
Exit;
end;
if (Length(S1) < Length(S2)) then begin
Result := -1;
Exit;
end;
// Same length, compare digits from left to right:
i := 1;
while (i <= Length(S1)) do begin
if (Ord(S1[i]) < Ord(S2[i])) then begin
Result := -1;
Exit;
end
else
if (Ord(S1[i]) > Ord(S2[i])) then begin
Result := 1;
Exit;
end;
Inc(i);
end;
end;
procedure Test;
var
SL: TMyStringList;
s: String;
begin
SL:= TMyStringList.Create;
try
SL.Add('1');
SL.Add('99999999999999999999999999999');
SL.Add('88888888888888888888888888888');
SL.Add('99999999999999999999');
SL.Sort;
for s in SL do WriteLn(s);
finally
SL.Free;
end;
end;
begin
Test;
ReadLn;
end.
出力:
1
99999999999999999999
88888888888888888888888888888
99999999999999999999999999999
更新:
数値が負の値である可能性がある場合は、このコンパイラで修正することができますrison試験:
function TMyStringList.CompareStrings(const S1, S2: string): Integer;
var
i : Integer;
cmpNegative : Boolean;
const
cNeg : array[boolean] of Integer = (1,-1);
begin
// Trimming leading/trailing spaces and leading zeroes might be needed first
Result := 0;
cmpNegative := false;
// Test for negative numbers
if (S1[1] = '-') then begin
if (S2[1] <> '-') then begin
Result := -1;
Exit;
end;
// Both numbers negative, reverse comparison
cmpNegative := true;
end
else
if (S2[1] = '-') then begin
Result := 1;
Exit;
end;
// Compare length, shortest sorts first
if (Length(S1) > Length(S2)) then begin
Result := 1*cNeg[cmpNegative];
Exit;
end;
if (Length(S1) < Length(S2)) then begin
Result := -1*cNeg[cmpNegative];
Exit;
end;
i := 1;
while (i <= Length(S1)) do begin
if (Ord(S1[i]) < Ord(S2[i])) then begin
Result := -1*cNeg[cmpNegative];
Exit;
end
else
if (Ord(S1[i]) > Ord(S2[i])) then begin
Result := 1*cNeg[cmpNegative];
Exit;
end;
Inc(i);
end;
end;
は、あなたは大きな整数パッケージを使用することを検討して、値を算術演算を行うために必要がある場合。 Delphi fast plus big integer?
私の議決権の行使にもかかわらず、私はマイナスの数字とマイナス記号も扱っています。 –
@LURDはすでにリストにリンクされています。 [BigNumbers](https://github.com/rvelthuis/BigNumbers):Docs [ここから開始](http://www.rvelthuis.de/programs/bigintegers.html)をお勧めしたいと思います。 –
@MarkSetchell、ありがとう、負の数のテストも追加されました。 –