poj 1588 Reverse Roman Notation

poj 1588 Reverse Roman Notation,第1张

poj 1588 Reverse Roman Notation
#include<cstdio>#include<cstring>using namespace std;char s[8]="IVXLCDM";int b[7]={1,5,10,50,100,500,1000};int ToDec(char *str){    int n,k,i,j,c[33];    n=(int)strlen(str);    for(i=0;i<n;i++)        for(j=0;j<7;j++) if(str[i]==s[j]) {     c[i]=b[j];     break; }    c[n]=0;    for(i=k=0;i<n;i++)        if(c[i+1]>c[i]) k-=c[i];        else k+=c[i];    return k;}void ToRoman(int k,char *str){    int i,j,m;    for(i=6,j=0;i>=0;i--)    {        while(k>=b[i]) str[j++]=s[i],k-=b[i];        if(!k) break;        if(i&1) m=i-1;        else m=i-2;        if(k>=b[i]-b[m])        { k-=b[i]-b[m]; str[j++]=s[m]; str[j++]=s[i];        }    }    str[j]='';}int main(){    char str[33];    int k,i,j,stk[1111];    for(i=j=0;scanf("%s",str)+1;)    {        if(str[0]=='=')        { if(!i) {     puts("stack underflow");     continue; } if(stk[i-1]<=0||stk[i-1]>4999)     puts("out of range exception"); else     ToRoman(stk[i-1],str),puts(str);        }        else if(str[0]=='+'||str[0]=='-'||str[0]=='*'||str[0]=='/')        {     if(i<2) {     puts("stack underflow");     continue; } if(str[0]=='+')     stk[i-2]=stk[i-1]+stk[i-2]; else if(str[0]=='-')     stk[i-2]=stk[i-2]-stk[i-1]; else if(str[0]=='*')     stk[i-2]=stk[i-1]*stk[i-2]; else {     if(!stk[i-1])         puts("division by zero exception");     else         stk[i-2]=stk[i-2]/stk[i-1]; } i--;        }        else stk[i++]=ToDec(str);    }    return 0;}

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/4922204.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-11-12
下一篇 2022-11-12

发表评论

登录后才能评论

评论列表(0条)

保存