#include <iostream>
#include <string>
#include <vector>
using namespace std;
class Mint {
public:
Mint();
Mint(int);
Mint (const char *s);
string afficher();
Mint operator+=(const Mint &rhs); //returns mint + rhs
Mint operator+(const Mint &rhs);
private:
vector<char> num;
};
#include "Mint.h"
#include <string.h>
Mint::Mint()
{
num.push_back(0);
}
Mint::Mint(int n)
{
while(n!=0)
{
num.push_back(n%10);
n = n/10;
}
}
Mint::Mint(const char* s)
{
int i = 0 ;
for(i=strlen(s)-1;i>=0;i--)
num.push_back(s[i] - '0');
}
string Mint::afficher(){
string s="";
int i;
for(i=num.size()-1;i>=0;i--)
s += char('0'+num[i]);
return s;
}
Mint Mint::operator+=(const Mint &rhs) {
unsigned int len = num.size();
char carry = 0;
if (len > rhs.num.size())
len = rhs.num.size();
unsigned int i;
for (i = 0; i <= len - 1; i++)
{
char result = num[i] + rhs.num[i] + carry;
num[i] = result % 10;
carry = result / 10;
}
while (carry)
{
if (i < num.size())
{
num[i] += carry;
if (num[i] >= 10)
{
num[i] -= 10;
i++;
}
else
carry = 0;
}
else {
num.push_back(carry);
carry = 0;
}
}
return *this;
}
Mint Mint::operator+(const Mint &rhs){
Mint result;
result = *this;
return result+=rhs;
}
#include "Mint.h"
#include <iostream>
#include <string>
using namespace std;
int main()
{
Mint x="123456",z="22222222222222222222",f;
Mint a = "655478461469974272005572";
Mint b = 8;
x += z;
f = x + z;
cout << x.afficher()<<endl;
}
hello everyone please check out this code and tell me why is the operator += only works if the numbers have the same size when i tried x += z; i got 345678 i think the problem is int for (i = 0; i <= len - 1; i++) loop i tried to fix it but i wasn't successful any solutions ?
Aucun commentaire:
Enregistrer un commentaire