zoukankan      html  css  js  c++  java
  • 《Delphi 算法与数据结构》学习与感悟[3]: 获取一个字节中非空位的个数

    一个字节有 8 个位, 这些位可能是 0 也可能是 1; 现在要算出一个字节中是 1 的位共有多少个.

    第一种方法是一个函数;
    第二种方法笨了点, 是先把 256 种可能值给一个数组, 随时调取.

    第一种方法虽然灵巧, 但不如第二种方法快(作者书中说: 在非特殊情况下, 一般要快到 10 倍左右);
    第二种方法虽然快捷, 并且使用方便, 但要以 256 个字节的数组空间为代价.
    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.
    
    那个小函数, 琢磨了半天才明白(惭愧); 以后判断其他数也没问题了, 譬如判断 Integer:
    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;
    
  • 相关阅读:
    第四节:前端自动化准备和详细配置(NVM、NPM/CNPM、NodeJs、NRM、WebPack、Gulp/Grunt、Git/SVN)
    第二十三节: EF性能篇(三)之基于开源组件 Z.EntityFrameWork.Plus.EF6解决EF性能问题
    第三节:一些指令总结(Nuget、)
    第十七节:易混淆的概念(静态和非静态、拆箱和装箱)
    Java使用Log4记录日志
    Java读取xml
    C# int.ToString() 常用参数说明
    WebAPI获取客户端请求数据
    Zend Studio获取永久使用权
    template.js 模版内调用外部JS方法
  • 原文地址:https://www.cnblogs.com/del/p/1110632.html
Copyright © 2011-2022 走看看