题目描述
定义一个四进制的类,重定义“+”号实现四进制数的累加。
输入
第一行输入所需要的四进制数的个数
第二行开始,依次输入四进制数
输出
所有输入四进制数累加的和
//
输入示例:
3
13
2
21
输出示例:
102
AC代码:
#include <iostream>
#include <string>
using namespace std;
class Quaternary
{
private:
string value;
public:
Quaternary(string val) : value(val) {}
Quaternary operator+(const Quaternary &other)
{
string result = "";
int carry = 0;
int len1 = value.length(), len2 = other.value.length();
int maxlen = max(len1, len2);
for (int i = 0; i < maxlen; i++)
{
int digit1 = (i < len1) ? value[len1 - 1 - i] - '0' : 0;
int digit2 = (i < len2) ? other.value[len2 - 1 - i] - '0' : 0;
int sum = digit1 + digit2 + carry;
result = to_string(sum % 4) + result;
carry = sum / 4;
}
if (carry > 0)
{
result = to_string(carry) + result;
}
return Quaternary(result);
}
friend ostream &operator<<(ostream &os, const Quaternary &q)
{
os << q.value;
return os;
}
};
int main()
{
int n;
cin >> n;
string input;
cin.ignore();
cin >> input;
Quaternary result(input);
for (int i = 1; i < n; i++)
{
cin >> input;
Quaternary num(input);
result = result + num;
}
cout << result << endl;
return 0;
}
标签:string,int,value,运算符,carry,result,Quaternary,加法,重载
From: https://blog.csdn.net/zgy11026/article/details/139249015