pku 1489解题报告

来源:互联网 发布:用winhex怎么恢复数据 编辑:程序博客网 时间:2024/06/06 03:26
 

埃及乘法 二进制 打表

一.题意:

1.几个的符号分别代表1,10,100,1000,10 000

2.计算a*b,b用二进制表示。

3.第一列从1开始,用c表示,第二列从a。每次翻倍,当c>b时,结束。如果,c的二进制表示能表示b的二进制,加*号。最后,把带*号的c加起来,就是结果

二.思路:

1.处理输入tran(): 翻译a,b->ta,tb

用tr[]数组可以简短代码长度,下标用字符的ASCII码表示;用指针也可简短代码长度,不过,这是我第一次这样用,尝试一下

2.翻倍:

c,ta每次翻倍,要翻译成埃及字符,用trans()函数

trans 先计算1的个数(用取模),再是10…

3.判断c是否能构成tb(二进制),用按位与运算’&’,这是一个简单的方法,在网上找的

4.处理输出格式

5.答案:可以直接把ta*tb的结果用埃及字符表示输出

三.代码

  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include<string.h>
  4. char a[110],b[110],t[]={"|n98r"};
  5. int tr[125],f[]={1,10,100,1000,10000,100000,100000};//后补两个构成6元素
  6. //'|'=124  输出 34
  7. int tran(char *a)
  8. {int ta=0;
  9.  while(*a)ta+=tr[*a++]; 
  10.  return ta;
  11. }
  12. void trans(int a,char *x)
  13. {
  14.  int i,n=0,mo;
  15.  for(i=0;i<5;i++)
  16.  {
  17.    mo=a%f[i+1]/f[i];//妙哉
  18.    if(mo)
  19.    {
  20.     while(mo--)x[n++]=t[i];
  21.     x[n++]=' ';    
  22.    }    
  23.  }x[n]=0;    
  24. }
  25. int main()
  26. {
  27. int ta,tb,i,c;
  28. char m1[100],m2[100];
  29. tr['|']=1,tr['n']=10,tr['9']=100,tr['8']=1000,tr['r']=10000;
  30. while(gets(a),strlen(a))
  31. {
  32.  gets(b); c=1;                   
  33.  ta=tran(a);tb=tran(b);int tmp=ta;
  34.  for(i=0;c<=tb;c*=2,ta*=2,i++)
  35.  {
  36.    trans(c,m1);
  37.    trans(ta,m2);
  38.    printf("%s%c",m1,(tb&c)?'*':' ');//位与   
  39.    int yu=34-1-strlen(m1);
  40.    while(yu--)putchar(' ');
  41.    puts(m2);                       
  42.  }trans(tmp*tb,m1);
  43.  printf("The solution is: %s\n",m1);          
  44. }
  45.       system("pause");
  46.       return 0;
  47. }

四.通过这道题,掌握了&运算,更熟练的运用了指针和逗号运算符

 

补充:

&也可以做位运算(主要是针对二进制),表示“按位与”运算

如果两个数相应的二进位都是1,那么该位的结果值也是1,否则为0

比如:

0&0=0,0&1=0,1&0=0,1&1=1

 

原创粉丝点击