晟锋软件公司机试

        今天去晟锋软件公司机试了.一共6道题,时间为3小时.前5道很普通,简单.后一道的工作量有点大----直接输多项式字符串进行运算.当时只是把二叉树做完就没时间了,很是不爽,就差一点了,于是下来接着做.自己随便做着没压力,花了半个小时就完成了调试字符串的递归建树与树的递归运算.
贴上劣作代码,算是对自己的激励.欢迎遇到此题的同志拍砖,呵呵

//为使算法直观易懂,建立二叉树时不进行数字字符转换成相应的整数,在计算时才互相转换,直观但效率很低

#include "stdafx.h"
#include "iostream.h"
#include "string.h"

//转换函数,不能转换小数与负数,计算步骤中不能出现负数与小数
int convert(char *p)//将数字字符转换成相应的整数,以便进行计算
{
int A=0;
int* a=new int[strlen(p)];
 for(int i=strlen(p)-1;i>=0;i--)
 {
 a[i]=p[i]-48;
 int s=1;
  for(int j=1;j<=(strlen(p)-i-1);j++)s=s*10;
 A=a[i]*s+A;
 }
delete[] a;
return A;
}

char* convert(int p)//将整数转换成相应的数字字符,以便进行计算
{int s=0,c=0;
 for(int a=p;a>=1;a=int(a/10))s++;
char* A=new char[s+1];
A[s]='/0';
 for(double aa=(double)p/10;aa>=0.1;aa=aa/10)
 {int b=aa*10-(int)aa*10;
 A[s-c-1]=(char)(b+48);
 c++;
 }
return A;
delete[] A;
}

 


//二叉树结构
struct tree
{
 char data[12];
 tree* nodel;
 tree* noder;
};

//建立 er cha shu,并按运算优先级排序,运算时就从最底下的两片叶子开始,此函数没问题
//可以在建树时进行运算,但为了算法的可读性,另写一函数计算
tree * createtree(char* shi,int l,int r,tree* headl,tree* headr)
{//先提取+-,采用快速排序的二分法思想对多项式进行递归分解
 tree* node=new tree;
 node->nodel=0;
 node->noder=0;
 char* temp=shi;
 for(temp+=r;temp>=shi+l;temp--)
 {
  if(*temp=='+'||*temp=='-')
  {
   node->data[0]=*temp;
   node->data[1]=0;
   if(headl!=0) headl->nodel=node;
   createtree(shi,l,(int)temp-(int)shi-1,node,0);
   if(headr!=0) headr->noder=node;
   createtree(shi,(int)temp-(int)shi+1,r,0,node);
   return node;
  }
 }
 temp=shi;
 for(temp+=r;temp>=shi+l;temp--)
 {
  if(*temp=='*'||*temp=='/')
  {
   node->data[0]=*temp;
   node->data[1]=0;
   if(headl!=0) headl->nodel=node;
   createtree(shi,l,(int)temp-(int)shi-1,node,0);
   if(headr!=0) headr->noder=node;
   createtree(shi,(int)temp-(int)shi+1,r,0,node);
   return node;
  }
 }
 temp=shi;
 for(temp+=r;temp>=shi+l;temp--)
 {
  if(*temp>='0'||*temp<='9')//ke yi bu pan duan
  {
   node->data[(int)temp-(int)shi-l]=*temp;
   node->data[(int)temp-(int)shi-l+1]=0;
   if(headl!=0) headl->nodel=node;
   if(headr!=0) headr->noder=node;
   return node;
  }

 }
}

//遍历tree并求值,递归式
void count(tree* node)
{
 if(node->nodel)
 {
  count(node->nodel);
  count(node->noder);
 switch(node->data[0])
 {
 case '+':{strcpy(node->data,convert(convert(node->nodel->data)+convert(node->noder->data)));break;}
 case '-':{strcpy(node->data,convert(convert(node->nodel->data)-convert(node->noder->data)));break;}
 case '*':{strcpy(node->data,convert(convert(node->nodel->data)*convert(node->noder->data)));break;}
 case '/':{strcpy(node->data,convert(convert(node->nodel->data)/convert(node->noder->data)));break;}
 
 }
 }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章