/**Define a structure / class to hold a very big number
(way bigger than bigint) and add a member functions to
increment the number by 1 and decrement the number by 1
- Dee on November 06, 2012 in United States | Report Duplicate */
/**Use an array to simulate bits.
Need to take care of carry's when add/substract.
One trivial bug: negative zero.
*/
#include <array>
#include <algorithm>
#include <iostream>
using namespace std;
class HugeNumber{
private:
static const int DIGITS = 1000;
array<unsigned short, DIGITS> number;//number[0] is the lowest digit
bool negative_flag;
public:
HugeNumber(){
number.fill(0);negative_flag = false;
}
HugeNumber(int number_int){
this->assign(number_int);
}
HugeNumber(HugeNumber const& n2){
negative_flag = n2.negative_flag;
for(unsigned int ii = 0; ii < DIGITS; ++ii)
number[ii] = n2.number[ii];
}
HugeNumber& assign(int number_int){
negative_flag = (number_int < 0);
if (negative_flag) number_int = -number_int;
for(unsigned int ii = 0; number_int; ++ii){
number[ii] = number_int%10;
number_int /= 10;
}
return *this;
}//assign
HugeNumber& operator++(){
if (negative_flag){
if (count(number.begin(),number.end(), 0) == DIGITS){//0
negative_flag = false;
++number[0];
return *this;
}
negative_flag = false;
--(*this);
negative_flag = true;
return (*this);
}
++number[0];
for(unsigned int ii = 0; ii < DIGITS-1 && number[ii] >= 10; ++ii){
number[ii] -= 10;
++number[ii+1];
}
return *this;
}
HugeNumber& operator--(){
if (count(number.begin(), number.end(), 0) == DIGITS){
negative_flag = true;
++number[0];
return *this;
}
if (negative_flag){
negative_flag = false;
++(*this);
negative_flag = true;
return (*this);
}
for(unsigned int ii = 0; ii < DIGITS; ++ii){
number[ii] = 9 - number[ii];
}
++(*this);
for(unsigned int ii = 0; ii < DIGITS; ++ii){
number[ii] = 9 - number[ii];
}
return *this;
}
void output(ostream& os) const{
if (negative_flag) os<<'-';
for(unsigned int ii = DIGITS-1; ii > 0; --ii){
if (!number[ii]) continue;
os<<number[ii];
}
os<<number[0];//in case all digits are zero
}
};
ostream& operator<<(ostream& os, HugeNumber& const number){
number.output(os);
return os;
}
int main(){
cout<<"hello"<<endl;
HugeNumber hn;
hn.assign(-2);
cout<<hn<<endl;
++hn;
cout<<hn<<endl;
++hn;
cout<<hn<<endl;
++hn;
cout<<hn<<endl;
++hn;
cout<<hn<<endl;
++hn;
cout<<hn<<endl;
--hn;
cout<<hn<<endl;
--hn;
cout<<hn<<endl;
--hn;
cout<<hn<<endl;
--hn;
cout<<hn<<endl;
--hn;
cout<<hn<<endl;
return 0;
}
Solving problems is fun. But solving the same problem over and over is pain. Once solved, forever solved.
sourcecode
Wednesday, November 14, 2012
Big number
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment