Polynomial Problem
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 1152 Accepted Submission(s): 459
Problem Description
We have learned how to obtain the value of a polynomial when we were a middle school student. If f(x) is a polynomial of degree n, we can let
If we have x, we can get f(x) easily. But a computer can not understand the expression like above. So we had better make a program to obtain f(x).
Input
There are multiple cases in this problem and ended by the EOF. In each case, there are two lines. One is an integer means x (0<=x<=10000), the other is an expression means f(x). All coefficients ai(0<=i<=n,1<=n<=10,-10000<=ai<=10000) are integers. A correct expression maybe likes
1003X^5+234X^4-12X^3-2X^2+987X-1000
Output
For each test case, there is only one integer means the value of f(x).
Sample Input
3
1003X^5+234X^4-12X^3-2X^2+987X-1000
Sample Output
264302
Notice that the writing habit of polynomial f(x) is usual such as
X^6+2X^5+3X^4+4X^3+5X^2+6X+7
-X^7-5X^6+3X^5-5X^4+20X^3+2X^2+3X+9
X+1
X^3+1
X^3
-X+1 etc. Any results of middle process are in the range from -1000000000 to 1000000000.
表达式求值
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
typedef __int64 TYPE;
TYPE xx[15];
char str[10005], s[10005];
void get(int x)
{
__int64 i, t = x;
xx[0] = 1;
for(i = 1; i<=10; i++)
{
xx[i] = t;
t *= x;
}
}
TYPE solve()
{
TYPE ans, c1, c2, n;
int i, len = strlen(s);
int op = 0;//op=1表示加 |op=2表示减
bool flag, flag2;
i = 0;
c1 = 0, c2 = 0;//c1代表x前的数字,c2代表x的次方数
n = 0;
ans = 0;
flag = false;
while(i<=len)
{
if( s[i] == '+' || s[i] == '-' || s[i] == 0x00)//0x00只是为了强调就是数字0,
//就是为了ASCII码转换的数字0!不是字符‘0’!
//避免手误将数字0写作字符‘0’,那就达不到用‘ ’清空字符串的目的了
{
c2 = xx[n];
//根据操作符进行运算
if(op == 1)//加
{
ans += (c1 * c2);
flag = false;
//printf( "ans:%I64d/n", c1*c2);
}
if(op == 2)//减
{
ans -= (c1 * c2);
flag = false;
//printf( "ans:-%I64d/n", c1*c2);
}
//首先读取操作符
if(s[i] == '+')
op = 1;
if(s[i] == '-')
op = 2;
i++;
c1 = 0, c2 = 0, n = 0;
}
else
{
//读取X前面的数字
while(s[i] >= '0' && s[i] <= '9')
{
flag = true;
c1 = c1*10 + s[i] - '0';
i++;
}
if(s[i] == 'X')
{
//前缀为空
if(c1 == 0 && flag == false)
c1 = 1;
i++;
//X的后缀为空
if (s[i] != '^')
n = 1;
}
if(s[i] == '^')
{
i++;
//读取^后面的数字
while(1)
{
if(s[i] == '+' || s[i] == '-' || s[i] == 0x00)
break;
n = n*10 + s[i] - '0';
i++;
}
}
}
}
//printf("#%d/n", ans);
return ans;
}
int main()
{
int x;
while(scanf("%d%s", &x, str) != EOF)
{
get(x);
if(str[0] != '-')
{
//所有字符串前缀都以符号开始,比较好处理
s[0] = '+';
strcpy(&s[1], str);//把字符串赋给从s[1]位置开始
}
else
{
strcpy(s, str);
}
printf("%I64d
", solve());
}
return 0;
}