定义一个四进制的类,重定义“+”号实现四进制数的累加。
输入:第一行输入所需要的四进制数的个数
第二行开始,依次输入四进制数。
输出:所有输入四进制数累加的和。
代码:
#include<iostream>
#include<string>
#include<cmath>
using namespace std;
class Four {
public:
string number;
void setnumber(string number) {
this->number = number;
}
int changetodec(){
int decimal = 0;
int power = 0;
for (int i = number.length() - 1; i >= 0; --i) {
int digit = number[i] - '0';
decimal += digit * pow(4, power);
power++;
}
return decimal;
}
string changetofour(int num) {
string result = "";
if (num == 0) {
result = "0";
}
while (num!= 0) {
int remainder = num % 4;
result = to_string(remainder) + result;
num /= 4;
}
return result;
}
Four operator+(Four& four) {
Four f1;
int number1 = this->changetodec();
int number2 = four.changetodec();
int number3 = number1 + number2;
string result = changetofour(number3);
f1.setnumber(result);
return f1;
}
};
int main() {
int count = 0;
cin >> count;
Four four;
four.setnumber("");
for (int i = 1;i <= count;i++) {
Four f;
string number;
cin >> number;
f.setnumber(number);
four=four + f;
}
cout << four.number << endl;
return 0;
}
涉及算法:十进制转四进制,四进制转十进制,