: 여기에 내 코드 오프 예입니다.
길이를 먼저 비교하고 동일한 경우 왼쪽에서 오른쪽으로 문자를 비교하는 것이 좋은 전략입니다.
NB. 문자열에 후행 또는 선행 공백이 있으면 0을 앞설 수 있으므로 비교하기 전에 제거하십시오. 여기
은 (델파이 동작과 프리 파스칼 함)의 오름차순 (문자열 등)의 값을 정렬하는 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
업데이트 :
숫자가 음수 일 수있는 경우이 compa에서 수정할 수 있습니다. 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, 감사합니다. 음수에 대한 테스트도 추가되었습니다. –