题意: 输入一个小数底,跟一个整数指数。输出幂。
思路:题目要注意输入的时候 要去掉前导零; 记录小数点位数(strchr()函数);
算法复杂度:o(N^2)N是底数位数。
代码:
#include <cstdio>
#include <cstring>
using namespace std;
#define MAX_N 2000
void toDigitReverse(char *, int *);
void toPow(int *, int, int, int *rslt);
void outputRslt(int *, int);
void toMultiply(int *, int, int *, int);
int main()
{
char strR[MAX_N];
int n;
char *radixP;
int radixNum;
int digitR[MAX_N];
int lenR;
int rslt[MAX_N];
while (scanf("%s %d", strR, &n) == 2) {
// init
memset(digitR, 0, sizeof(digitR));
memset(rslt, 0, sizeof(rslt));
// count radix num
int tp_len = strlen(strR);
for (int i = tp_len - 1; strR[i] == '0'; i--) {
strR[i] = '\0';
}
radixP = strchr(strR, '.');
radixNum = strlen(radixP + 1);
radixNum = radixNum * n;
// delete radix
*radixP = '\0';
radixP++;
if (strR[0] == '0') { //0.xxx
strcpy(strR, radixP);
}else {
strcat(strR, radixP);
}
lenR = strlen(strR);
// to digit
toDigitReverse(strR, digitR);
// to pow
toPow(digitR, lenR, n, rslt);
// to output
outputRslt(rslt, radixNum);
// end a cases
}
return 0;
}
void toDigitReverse(char *strR, int *digitR)
{
int len = strlen(strR);
for (int head = 0, tail = len - 1; head < len; head++, tail--) {
digitR[head] = strR[tail] - '0';
}
}
void toPow(int *digitR, int lenR, int n, int *rslt)
{
// rslt = digit at first
for (int i = 0; i < lenR; i++) {
rslt[i] = digitR[i];
}
n--;
for (int i = 0; i < n; i++) {
toMultiply(rslt, MAX_N, digitR, lenR); // xx to be continue
}
}
void outputRslt(int *rslt, int radixNum)
{
int tail;
for (tail = MAX_N - 1; !rslt[tail] && tail >= radixNum; tail--) {
}
radixNum--; // index of rslt is from 0 1 2
while (tail > radixNum) {
printf("%d", rslt[tail--]);
}
printf(".");
while (tail >= 0) {
printf("%d", rslt[tail--]);
}
printf("\n");
}
void toMultiply(int *rslt, int lenRslt, int *digitR, int lenR)
{
int tmp[MAX_N];
memset(tmp, 0, sizeof(tmp));
for (int i = 0; i < lenRslt; i++) {
for (int j = 0; j < lenR; j++) {
tmp[i + j] += rslt[i] * digitR[j];
}
}
int ans = 0;
for (int i = 0; i < MAX_N; i++) {
rslt[i] = (tmp[i] + ans) % 10;
ans = (tmp[i] + ans) / 10;
}
}