c++大整数的表示及应用

大家知道在c++中经常会出现整数溢出的情况。如果运算结果真的很大,就需要用到所谓的高精度算法,即用数组来存储整数,并模拟手算的方法进行四则运算。下面介绍的方法是,将一个大整数,封装成struct,用的时候,跟int用法一样。

#include <iostream>
#include <stdio.h>
#include <string.h>
#include <vector>
using namespace std;
struct BigInteger{


    static const int BASE = 100000000;
    static const int WIDTH = 8;
    vector<int> s;

    BigInteger(long long num = 0) {*this = num;}//构造函数,就只是设个初值,没什么用


    BigInteger operator = (string str){ //赋值运算符 当等号右边是数字字符串时,重载等号运算符 可以用x="123456789546545"这样的方式来给x赋值
        s.clear();
        int x, len = (str.length() -1)/WIDTH +1;
        for(int i = 0;i<len; i++){
            int end = str.length() - i*WIDTH;
            int start = max(0, end-WIDTH);
            sscanf(str.substr(start, end-start).c_str(),"%d", &x);
            s.push_back(x);
        }
        return *this;

    }


    BigInteger operator = (long long num) {//赋值运算符 当等号右边是 long long类型时,可以用x=1234567895这样的方式来给x赋值
        s.clear();
        do{

            s.push_back(num%BASE);//在s中每次存8位,这样速度快,当然不够8位就存自身的长度。比如输入123456789123456789. 那么s中就是 {23456789,34567891,12}

            num /= BASE;
        }while(num>0);
        return *this;
    }
};


ostream& operator << (ostream &out,  const BigInteger& x) {//重载输出运算符
    out<< x.s.back();
    for(int i= x.s.size()-2;i>=0; i--){
        char buf[20];
        sprintf(buf, "%08d", x.s[i]);
        for(int j=0;j<strlen(buf); j++) out<<buf[j];//输出的时候倒着输出s中内容。
    }
    return out;
}
istream& operator >> (istream &in,  BigInteger& x) {//重载输入运算符
    string s;
    if(!(in>>s)) return in;
    x = s;
    return in;
}


int main()
{
    BigInteger bigint1;
    BigInteger bigint2;
    bigint1 =  "123456789456123";
    cout<<"输入bigint2"<<endl;
    cin>>bigint2;
    cout <<bigint1 << endl;
    cout <<bigint2 << endl;
    return 0;

}

下面是运行结果,仅供参考:


猜你喜欢

转载自blog.csdn.net/yige__cxy/article/details/81062188