Description
Given a polynomial and the value of the variable x, you task is to calculate the value of the polynomial.
Input
The first line of the input is a positive integer T. T is the number of test cases followed.
In each test case, the first line contains two integer n and x (0<=n<=50, 0<=x<=10000). The second line contains n+1 integers, representing the coefficients of a polynomial from power degree N down to power degree 0, each integer is no less than 0 and no more than 10000.
Output
The output of each test case should consist one line, containing the result of the polynomial.
题目解释:求解多项式的值。多项式包括一个基数,还有n个权重。在这里输入基数为x,还有n个权重值a1,a2,a3。。。则有:
a1*xn + a2*xn-1 + a3*xn-2 +…+ an*x0
可以化解成:
= (…(((x+a1)*n+a2)*n+a3)+…)
(1)初始化一个数组 result[201]
(2)对于数组的每一位都乘以基数x,乘完后进行进位处理
(3)对于数组的最低位进行加权值操作。
#include <iostream>
#include <string.h>
#define MAX_LEN 201
using namespace std;
int result[MAX_LEN];
int main(){
int T;
cin >> T;
while (T > 0) {
int n, x;
cin >> n >> x;
memset(result, 0, sizeof(result));
for (int i = 0; i <= n; i++) {
int carray = 0;
for (int j = MAX_LEN - 1; j >= 0; j--) { // 对于数组每一个数都乘以x
result[j] = result[j] * x + carray;
carray = result[j] / 10;
result[j] = result[j] % 10;
}
int q;
cin >> q;
carray = q;
for (int j = MAX_LEN - 1; j >=0 ; j--) { // 对于数组最低位进行加权值操作
result[j] = result[j] + carray;
carray = result[j] / 10;
result[j] = result[j] % 10;
}
}
bool flag = false;
for (int i = 0; i < MAX_LEN; i++) {
if (result[i] != 0) { // 遇到了第一个不为0 的数
flag = true;
}
if (flag) cout << result[i];
}
cout << endl;
T--;
}
return 0;
}