看到同事桌上有一份面试题,有一个 36 进制运算的题目,手贱敲了一下,不调真的不好做啊
#include <stdio.h>
#include <string>
#include <algorithm>
#include <math.h>
int convert_36_10(std::string strNum) {
std::reverse(strNum.begin(), strNum.end());
int n = 0;
for (int i = 0; i < strNum.size(); i++) {
char c = strNum[i];
if (c >= '0' && c <= '9') {
n += (c - '0') * pow(36.0, i);
} else if (c >= 'A' && c <= 'Z') {
n += (10 + c - 'A') * pow(36.0, i);
}
}
return n * ((strNum[strNum.size() - 1] == '-') ? -1 : 1);
}
std::string convert_10_36(int n) {
if (n == 0) {
return "0";
}
std::string strNum;
int s = n > 0;
n = abs(n);
while (n) {
int m = n % 36;
char c = '-';
if (m < 10) {
c = m + '0';
} else {
c = m-10 + 'A';
}
strNum = c + strNum;
n /= 36;
}
return s ? strNum : "-"+strNum;
}
std::string add(std::string strNum1, std::string strNum2) {
int n1 = convert_36_10(strNum1);
int n2 = convert_36_10(strNum2);
return convert_10_36(n1 + n2);
}
std::string min(std::string strNum1, std::string strNum2) {
int n1 = convert_36_10(strNum1);
int n2 = convert_36_10(strNum2);
return convert_10_36(n1 - n2);
}
int main() {
while (1) {
char szNum1[16] = {0}, szNum2[16] = {0};
scanf("%s%s", szNum1, szNum2);
printf("%s + %s = %s\n", szNum1, szNum2, add(szNum1, szNum2).c_str());
printf("%s - %s = %s\n", szNum1, szNum2, min(szNum1, szNum2).c_str());
}
return 0;
}