如果你想要做的唯一事情是比較包含可能比編譯器還內置例程,你可以比較字符串本身較大的數字的字符串。
首先比較長度,如果相同,比較從左到右的字符將是一個很好的策略。
注意:如果您的字符串包含尾部或前導空格,前導零,則在比較之前將其刪除。
下面是一個使用的StringList以按升序的值(字符串)排序的例子(應該在Delphi工作和FreePascal的):
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
更新:
如果數字可以是負值,那麼可以通過該比較來確定裏森測試:
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):文檔[從這裏開始](http://www.rvelthuis.de/programs/bigintegers.html)。 –
@MarkSetchell,謝謝,也爲負數添加了測試。 –