写在读前:
看了大佬们利用结构体与重载运算符写的大整数类;c++只会套用stl的菜鸡直呼🐂🍺的同时又深感无力;便写了这篇比较简单的利用vector模拟实现的大整数。
1. 定义:
typedef vector
<int
> Bigint
;
简洁明了,一个vector便可以模拟一个大整数,每位数字倒序储存在vector中,原则上来说vector中每个元素大小都不超过10;
2. 输入与赋值:
string number
;
cin
>>number
;
Bigint Big
=assigned(number
);
Bigint
assigned(string
& str
)
{
Bigint temp
;
for(int i
=str
.length()-1;i
>=0;i
--)
temp
.push_back((int)(str
[i
]-'0'));
return temp
;
}
3.比较:
bool compared(Bigint
& a
,Bigint
& b
)
{
if(a
.size()>b
.size()) return true;
else if(a
.size()<b
.size()) return false;
else{
for(int i
=0;i
<a
.size();i
++)
{
if(a
[i
]>b
[i
]) return true;
else if(a
[i
]<b
[i
]) return false;
}
}
}
4. 四则运算:
加法:
Bigint
added(Bigint
& a
,Bigint
& b
)
{
Bigint c
;
int lena
=a
.size(),lenb
=b
.size();
int len
=max(lena
,lenb
),next
=0;
for(int i
=0;i
<len
;i
++)
{
if(i
<lena
&&i
<lenb
) c
.push_back(a
[i
]+b
[i
]);
else if(i
<lena
&&i
>=lenb
) c
.push_back(a
[i
]);
else if(i
>=lena
&&i
<lenb
) c
.push_back(b
[i
]);
else break;
c
[i
]+=next
;
next
=c
[i
]/10;
if(i
!=len
-1) c
[i
]%=10;
}
return c
;
}
减法:
Bigint
diffed(Bigint
& a
,Bigint
& b
)
{
Bigint c
;
int lena
=a
.size(),lenb
=b
.size(),next
=0,mark
=0;
for(int i
=0;i
<lena
;i
++)
{
int temp
;
if(i
<lena
&&i
<lenb
){
if(a
[i
]-b
[i
]+next
<0) { c
.push_back(a
[i
]-b
[i
]+10+next
);next
=-1; }
else { c
.push_back(a
[i
]-b
[i
]+next
);next
=0;}
}else if(i
>=lenb
){
if(a
[i
]+next
<0) { c
.push_back(a
[i
]+10+next
);next
=-1; }
else { c
.push_back(a
[i
]+next
);next
=0;}
}else break;
}
for(int i
=c
.size()-1;i
>=0;i
--)
{
if(c
[i
]==0) continue;
else { mark
=i
;break; }
}
c
.resize(mark
+1);
return c
;
}
乘法:
Bigint
timesed(Bigint
& a
,Bigint
& b
)
{
int lena
=a
.size(),lenb
=b
.size(),mark
=0;
Bigint
c(lena
+lenb
,0);
for(int i1
=0;i1
<a
.size();i1
++)
{
for(int i2
=0;i2
<b
.size();i2
++)
{
c
[i1
+i2
]+=a
[i1
]*b
[i2
];
c
[i1
+i2
+1]+=c
[i1
+i2
]/10;
c
[i1
+i2
]%=10;
}
}
for(int i
=c
.size()-1;i
>=0;i
--)
{
if(c
[i
]==0) continue;
else { mark
=i
;break; }
}
c
.resize(mark
+1);
return c
;
}
更新于2020.7.4