建议大家先看一下我写的这个专题,https://blog.csdn.net/ericgipsy/article/details/80135017,数组模拟实现进制转换。
然后给一道题,八进制乘法,福建工程OJ一道题:
http://www.fjutacm.com/Contest.jsp?cid=434#P2
思路:
这题就普通的数组模拟,和我上次讲的专题套路一样,字符串读入,用atoi( )函数转成整数单独判0的情况,然后再声明整数数组,a[l1 – 1 – i] = s1[i] – ‘0’ ; 把角标调成从左往右的,然后自己手动模拟一下,写一下 八进制456 * 456的计算式,就能模拟出规律了。注意这题要考虑正负,别忘了对负号特判。
本人AC代码:
#include <cstdlib>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <map>
#include <vector>
#include <algorithm>
using namespace std;
typedef long long ll;
map <int, int> mp;
char s1[20], s2[20];
int a1[20], a2[20];
int ans[50];
int main() {
while(~scanf(“%s %s”, s1, s2)) {
int l1 = strlen(s1), l2 = strlen(s2);
int p = atoi(s1), q = atoi(s2);
if(p == 0 || q == 0) {
puts(“0”);
continue;
}
bool f1 = 0, f2 = 0;
if(s1[0] == ‘-‘) {
f1 = 1;
for(int i = 0; i < l1 – 1; i++) s1[i] = s1[i + 1];
l1–;
}
if(s2[0] == ‘-‘) {
f2 = 1;
for(int i = 0; i < l2 – 1; i++) s2[i] = s2[i + 1];
l2–;
}
memset(a1, 0, sizeof(a1));
memset(a2, 0, sizeof(a2));
memset(ans, 0, sizeof(ans));
for(int i = 0; i < l1; i++) a1[l1 – 1 – i] = s1[i] – ‘0’;
for(int i = 0; i < l2; i++) a2[l2 – 1 – i] = s2[i] – ‘0’;
int l = max(l1, l2);
int t = 0;
for(int i = 0; i <= l; i++) {
for(int j = 0; j <= l; j++) {
ans[i + j] += (a2[i] * a1[j] + t) % 8;
t = (a2[i] * a1[j] + t) / 8;
}
}
//for(int i = l * 2; i >= 0; i–) printf(“%d “, ans[i]);
//printf(“\n”);
for(int i = 0; i <= 2 * l; i++) {
ans[i + 1] += ans[i] / 8;
ans[i] %= 8;
}
int pos;
for(int i = 2 * l; i >= 0; i–) {
if(ans[i] != 0) {
pos = i; break;
}
}
if((!f1 && f2) || (f1 && !f2)) printf(“-“);
for(int i = pos; i >= 0; i–) printf(“%d”, ans[i]);
printf(“\n”);
}
}