Gray码生成

来源:互联网 发布:视频修改软件手机软件 编辑:程序博客网 时间:2024/06/13 01:16

方法一:

(1) 1阶Gray码是 0, 1;
(2) 设n>1, 且n-1阶Gray码已定义好,
      将n-1阶Gray码顺序列一遍, 接下来
      将n-1阶Gray码反序列一遍,
      顺序列的码每个前面添0,
      反序列的码每个前面添1.

var
  n,s,i,s1,k,j:longint;
  a:array[0..1000] of longint;
   procedure a10(x,dep:longint);
var
  i:longint;
begin
  if x<>0
  then begin
       a10(x div 2,dep+1);
       write(x mod 2);
       end;
  if x=0
  then begin
         for i:=1 to n-dep+1 do
           write(0);
       end;
end;
begin
  read(n);
  a[1]:=0;
  s:=1;
  for i:=1 to n do
    begin
      s1:=s;
      s:=s*2;
      k:=s1;
      for j:=s1 downto 1 do
        begin
          inc(k);
          a[k]:=a[j]+s1;
        end;
    end;
  for i:=1 to s do
    begin
      a10(a[i],1);
      writeln;
    end;
end.

方法2:

例如:二进制码0101,为4位数,所以其所转为之格雷码也必为4位数,因此可取转成之二进位码第五位为0,即0 b3 b2 b1 b0。


0 xor 0=0,所以g3=0


0 xor 1=1,所以g2=1


1 xor 0=1,所以g1=1


0 xor 1=1,所以g0=1


因此所转换为之格雷码为0111 

var
  a:array[0..10000] of longint;
  s,i,n:longint;
  procedure a10(x,dep:longint);
var
  i:longint;
begin
  if x<>0
  then begin
       a10(x div 2,dep+1);
       write(x mod 2);
       end;
  if x=0
  then begin
         for i:=1 to n-dep+1 do
           write(0);
       end;
end;
  procedure gray(x:longint);
var
  s,x1,x2,i:longint;
begin
  s:=0;
  x1:=x;
  a[x]:=0;
  while x1<>0 do
    begin
      inc(s);
      x1:=x1 div 2;
    end;
  for i:=1 to s do
    begin
      x1:=x and (1<<(i-1));
      x1:=(x1<<(s-i))>>(s-1);
      x2:=x and (1<<i);
      x2:=(x2<<(s-i-1))>>(s-1);
      a[x]:=a[x]+((x1 xor x2)<<(i-1));
   end;
  a10(a[x],1);
  writeln;
end;
begin
  read(n);
  s:=1;
  for i:=1 to n do
    s:=s*2;
  for i:=0 to s-1 do
    gray(i);
end.


1 0