题目来源
题目描述
题目解析
这道题不难,考察两个知识点:
- 第一:检查输入是否正确
- 第二:进制计算
- 我们先将数字转换为十进制
- 然后用十进制计算出结果
- 最后将结果转换为原进制
#include <vector>
#include <set>
#include <queue>
#include <stack>
#include <functional>
#include <sstream>
#include <iostream>
#include <algorithm>
#include <map>
#include <random>
#include <ctime>
#include <iterator>
using namespace std;
class Solution{
private:
// 检查是否合法
bool checkRadix(int radix){
return (radix >= 2 && radix <= 35);
}
bool checkNum(std::string &str){
if(str.empty() ||
(str.front() == '0' && str.size() != 1) ||
str.size() > 100){
return false;
}
if(str.front() == '0' && str.size() != 1){
return false;
}
for(auto ch : str){
if(!isdigit(ch) && !islower(ch)){
return false;
}
}
return true;
}
private:
// 1101
// 十进制转换为N进制
std::string ten2Nbase(int num, int N){
char tmp[64] {0};
itoa(num, tmp, N);
return tmp;
}
// N进制转换为十进制
int NBaseToTen(std::string &str, int radix){
return strtol(str.c_str(), NULL, radix);
}
struct Info{
int pos;
std::string str;
Info(int pos, std::string str):pos(pos), str(str){
}
};
Info calN(int radix, std::string first, std::string second){
// N进制转换为十进制
int f1 = NBaseToTen(first, radix);
int f2 = NBaseToTen(second, radix);
int t = f1 - f2;
return Info(t < 0 ? 1 : 0,ten2Nbase(t, radix));
}
public:
Info process(int radix, std::string first, std::string second){
if(!checkRadix(radix) || !checkNum(first) || !checkNum(second)){
return {-1, ""};
}
return calN(radix, first, second);
}
};
int main(){
Solution a;
auto ans = a.process(2, "11", "1");
std::cout << ans.pos << "\t" << ans.str <<"\n";
ans = a.process(8, "07", "1");
std::cout << ans.pos << "\t" << ans.str <<"\n";
}