有点杂乱无章,考虑各种情况就行了。
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
using namespace std;
#define INF 0x3fffffff
#define MAXN 100001
int main()
{
int n,m, x, flag, mul, ans;
char str[MAXN];
while(~scanf("%d",&x)){
scanf("%s",str);
int len = strlen(str);
int num = -INF;
flag = 1;
ans = 0;
for(int i = 0; i < len; i++){
if(str[i] == '-'){
flag = 0;
if(i + 1 < len && str[i + 1] == 'X')num = 1;
continue;
}
if(str[i] == '+'){
flag = 1;
if(i + 1 < len && str[i + 1] == 'X')num = 1;
continue;
}
if(str[i] == 'X'){
if(i-1<0)num = 1;
if(!flag)num = -num;flag = 1;
if((i + 1 < len && str[i+1] != '^')||i+1>=len)ans += num*x, num = -INF;
continue;
}
if(i - 1 >= 0 && str[i] >= '0' && str[i] <= '9' && str[i-1]== '^'){
if(i + 1 < len && str[i+1] >= '0' && str[i+1]<= '9'){
mul = (str[i] -'0')*10 + str[i+1] - '0';
i++;
}
else mul = str[i] -'0';
if(!flag)num = -num;flag = 1;
int mid = x;
for(int j = 2; j <= mul; j++){
mid *= x;
}
ans += num * mid;
num = -INF;
continue;
}
if(str[i] >= '0' &&str[i] <= '9'){
if(num == -INF)num = str[i] - '0';
else num = num*10 + str[i] - '0';
}
}
if(num != -INF){
if(!flag)num = -num;
ans += num;
}
printf("%d\n",ans);
}
return 0;
}
标签:hdu,str,int,len,flag,num,&&,Polynomial,Problem From: https://blog.51cto.com/u_16192154/6767465