大整数类
题解:
要实现大整数类,我们首先要设置多个构造器,使之能识别字符串作为数字,因为使用字符串可以输入很大的数字且不越界。
- 同时由于拿到的是字符串不是直接的数字了,所以我们还需要通过运算符重载来实现加法和等于。
如何实现字符串形式的加法?
- 我们先计算一下要加的两个字符串形式的数字的位数,我们使用给位数小的数字进行补0操作,使之位数相同且多补一位0防止进位,接着在二者位数相同的情况下,我们逐位相加,一旦大于10进位即可,再把原先补的多余的0判断是否要去掉即可。
代码:
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
class HugeInteger {
private:
string str;
public:
HugeInteger();
HugeInteger(int i);
HugeInteger(string s);
friend ostream & operator<<( ostream & os,HugeInteger & c);
string operator + (const HugeInteger & h) {
char stand = '0';
string b = h.str;
string a = this->str;
if(a.length()>b.length()){
while(a.length()>b.length()) {
b = stand + b;
}
}
if(a.length()<b.length()){
while(a.length()<b.length()) {
a = stand + a;
}
}
a = stand + a;
b = stand + b;
for(int i=a.length()-1; i>=0; i--) {
char tempSum = a[i] + b[i] - stand;
a[i] = tempSum;
if(a[i]>57) {
char temp = a[i] - 10;
a[i] = temp;
a[i-1] += 1;
}
}
a = a[0]==stand ? a.replace(0,1,""): a;
return a;
}
string operator + (string a) {
char stand = '0';
string b = this->str;
if(a.length()>b.length()){
while(a.length()>b.length()) {
b = stand + b;
}
}
if(a.length()<b.length()){
while(a.length()<b.length()) {
a = stand + a;
}
}
a = stand + a;
b = stand + b;
for(int i=a.length()-1; i>=0; i--) {
char tempSum = a[i] + b[i] - stand;
a[i] = tempSum;
if(a[i]>57) {
a[i] -= 10;
a[i-1] += 1;
}
}
a = a[0]==stand ? a.replace(0,1,""): a;
return a;
}
HugeInteger operator = (string & a) {
HugeInteger h(a);
return h;
}
};
HugeInteger::HugeInteger(string s) {
this->str = s;
}
ostream & operator<<( ostream & os,HugeInteger & c) {
os<<c.str;
return os;
}
HugeInteger::HugeInteger() {
str = "0";
}
HugeInteger::HugeInteger(int i) {
int k = i;
while(i) {
char tempchar = char( i%10 +48) ;
str = tempchar + str;
i/=10;
}
if(k==0){
str="0";
}
}
int main() {
HugeInteger n1( 7654321 );
HugeInteger n2( 7891234 );
HugeInteger n3( "99999999999999999999999999999" );
HugeInteger n4( "1" );
HugeInteger n5;
cout << "n1 is " << n1 << "\nn2 is " << n2
<< "\nn3 is " << n3 << "\nn4 is " << n4
<< "\nn5 is " << n5 << "\n\n";
n5 = n1 + n2;
cout << n1 << " + " << n2 << " = " << n5 << "\n\n";
cout << n3 << " + " << n4 << "\n= " << ( n3 + n4 ) << "\n\n";
n5 = n1 + 9;
cout << n1 << " + " << 9 << " = " << n5 << "\n\n";
n5 = n2 + "10000";
cout << n2 << " + " << "10000" << " = " << n5 << endl;
return 0;
}