《Delphi 算法与数据结构》学习与感悟[3]: 获取一个字节中非空位的个数

unit Unit1;

interface

uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls;

type
TForm1 = class(TForm)
Button1: TButton;
procedure Button1Click(Sender: TObject);
end;

var
Form1: TForm1;

implementation

{\$R *.dfm}

{方法1: 获取函数}
function GetByteBits(x: Byte): Byte;
begin
Result := 0;
while x <> 0 do
begin
if Odd(x) then Inc(Result);
x := x shr 1;
end;
end;

{方法2: 把所有可能的值放在一个常数数组}
const
BitArr: array[0..MAXBYTE] of Byte = (
0,1,1,2,1,2,2,3,1,2,2,3,2,3,3,4,1,2,2,3,2,3,3,4,2,3,3,4,3,4,4,5,
1,2,2,3,2,3,3,4,2,3,3,4,3,4,4,5,2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6,
1,2,2,3,2,3,3,4,2,3,3,4,3,4,4,5,2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6,
2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6,3,4,4,5,4,5,5,6,4,5,5,6,5,6,6,7,
1,2,2,3,2,3,3,4,2,3,3,4,3,4,4,5,2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6,
2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6,3,4,4,5,4,5,5,6,4,5,5,6,5,6,6,7,
2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6,3,4,4,5,4,5,5,6,4,5,5,6,5,6,6,7,
3,4,4,5,4,5,5,6,4,5,5,6,5,6,6,7,4,5,5,6,5,6,6,7,5,6,6,7,6,7,7,8);

{测试}
procedure TForm1.Button1Click(Sender: TObject);
var
b,num: Byte;
begin
b := 255;
num := GetByteBits(b);      {使用函数获取}
ShowMessage(IntToStr(num)); {8}
num := BitArr[b];           {直接使用数组获取}
ShowMessage(IntToStr(num)); {8}

b := 254;
num := GetByteBits(b);      {使用函数获取}
ShowMessage(IntToStr(num)); {7}
num := BitArr[b];           {直接使用数组获取}
ShowMessage(IntToStr(num)); {7}
end;

end.



function GetIntBits(x: Integer): Byte;
begin
Result := 0;
while x <> 0 do
begin
if Odd(x) then Inc(Result);
x := x shr 1;
end;
end;


posted on 2008-03-17 23:27  万一  阅读(...)  评论(...编辑  收藏