Delphi-PRAXiS

Delphi-PRAXiS (https://www.delphipraxis.net/forum.php)
-   Library: Algorithmen (https://www.delphipraxis.net/28-library-algorithmen/)
-   -   Delphi IsPowerOfTwo (https://www.delphipraxis.net/7039-ispoweroftwo.html)

negaH 31. Jul 2003 00:15


IsPowerOfTwo
 
Des öfteren möchte man testen ob eine Zahl eine Exponentation von 2 ist, zb. 1,2,4,8,16,32 usw. Dazu findet man immer wieder im WEB einen Source der so ähnlich ist wie der nachfolgende.

Delphi-Quellcode:
function IsPowerOfTwo(X: Cardinal): Boolean;
var
  I, Y : Integer;
begin
  Y := 2;
  for I := 1 to 32 do
  begin
    if X = Y then
    begin
      Result := True;
      Exit;
    end;
    Y := Y shl 1;
  end;
  Result := False;
end;
Aber wenn man sich ein bischen mit Boolscher Algebra auskennt weiß man das obiger Code viel zu ineffizient ist. Ich möchte hier nun zeigen wie es viel eleganter geht.

Delphi-Quellcode:
function IsPowerOfTwo(Value: Cardinal): Boolean;
begin
  Result := (Value > 0) and (Value and (Value -1) = 0);
end;
Das ist alles.

Gruß Hagen


Alle Zeitangaben in WEZ +1. Es ist jetzt 20:13 Uhr.

Powered by vBulletin® Copyright ©2000 - 2024, Jelsoft Enterprises Ltd.
LinkBacks Enabled by vBSEO © 2011, Crawlability, Inc.
Delphi-PRAXiS (c) 2002 - 2023 by Daniel R. Wolf, 2024 by Thomas Breitkreuz