大数运算(三)——大数相除求余数和商

描述:

输入两个超长的整型构成的字符串,使用空格隔开,求前者除以后者的余数

输入输出格式要求

输入的字符串最大长度为100个字符,输出商和余数,之间用空格隔开,如果结果异常输出NULL

样例:

输入:123456789 23456789

输出:5 6172844

#include
#include
using namespace std;

bool Compare(string first,string second)
{
    int i=0;
    while('0'==first[i])
        i++;
    first.erase(0,i);
    i=0;
    while('0'==second[i])
        i++;
    second.erase(0,i);
    int len1=first.size();
    int len2=second.size();
    if(len1return false;
    else if(len1==len2 && firstreturn false;
    return true;
}
string Subtraction(string s1,string s2)
{
    if(s1==s2)
        return "0";
    int len1=s1.size();
    int len2=s2.size();
    for(int i=len2-1;i>=0;i--)
    {
        s1[len1-1-i] ='0'+ s1[len1-1-i] -s2[len2-1-i];  //不要忘了加‘0’
    }
    //cout<
    for(int i=len1-1;i>=0;i--)
    {
        if(s1[i]<'0')
        {
            s1[i] += 10;
            s1[i-1]--;
        }
    }
    int i=0;
    while(s1[i]=='0')
        i++;
    s1.erase(0,i);  //去掉字符串前面的0
    //cout<
    return s1;
}
void BigDivision(string a,string b)
{
    string result,s;    //result用来保存商,s用来保存每次的运算时的被除数及最后的余数
    int count,i;
    if("0"==b)
    {
        //cout<<"Error,divisor can not be zero!"<
        cout<<"NULL"<return;
    }
    if(!Compare(a,b))
    {
        //cout<<"商:"<<0<<",余数:"<
        cout<<0<<" "<return;
    }
    int len=a.size();
    for(int i=0;i0;
        s.push_back(a[i]);
        while(Compare(s,b))
        {

            s=Subtraction(s,b);
            count++;
        }

        result+=char(count+'0');    //s>b时加每次相除得到的商或者,s
    }
    //cout<
    i=0;
    while('0'==result[i])
        i++;
    result.erase(0,i);
    i=0;
    while('0'==s[i])
        i++;
    s.erase(0,i);
    //cout<<"商为:"<
    cout<" "<int main()
{
    string str1,str2;
    while(cin>>str1>>str2)
    //cout<
        BigDivision(str1,str2);
}

程序运行结果:

大数运算(三)——大数相除求余数和商_第1张图片

你可能感兴趣的:(C/C++学习,华为机试)