Click here to Skip to main content
15,921,113 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
C++
class BigInteger
{
    public:
    void Subtraction()
    {
        string string1,string2;
        char x=0;
        cout<<"Enter first number :";
        cin>>string1;
        cout<<"Enter second number :";
        cin>>string2;
        size_t n=max(string1.size(),string2.size());
        if(n>string1.size())
            string1=string(n-string1.size(),'0')+string1;
        if(n>string2.size())
            string2=string(n-string2.size(),'0')+string2;
        string final(n,'0');
        string::const_reverse_iterator s1 = string1.rbegin(), e = string1.rend(), s2 = string2.rbegin();
        string::reverse_iterator f = final.rbegin();
        while (s1!=e)
        { 
            int ss1=*s1-'0';
            if(*s1-'0'<*s2-'0')
            {
                int m=ss1+10;
                ++s1;
                ss1--;
                --s1;
                x = m-(*s2-'0');
            }
            else 
            {
                x=ss1-(*s2-'0');	
            }
            *f = x + '0';
            ++s1;
            ++s2;
            ++f;     
        }
                       
        cout<< "final = " <<final << endl;
    }
};

when I enter number 1= 35
and number 2=6
the result = 39
in this line
ss1--;
the problem is when subtract one from second digit no change happened in the basic string
Posted
Updated 14-Dec-14 11:40am
v2
Comments
Sergey Alexandrovich Kryukov 14-Dec-14 18:53pm    
The whole idea to implement big integers based on string representation is utterly bad, so why considering some particular bugs?

Make a correct start, then we can discuss it. Don't use decimal system. As nearly all CPUs are byte-based, but, for unlimited-size numbers, you still need to use digit-by-digit algorithms, you have to use 256-ary systems or perhapes any other with 222 base.

Also, your class makes sense at all. Get rid of I/O, implement only arithmetic, constructors creating your number from some of the integer types and string and implement "to string" formatting.

—SA

1 solution

For mathematics you should convert the input string to a number ParseInt64 will do it for really big numbers.

C++
long number1 = Int64.Parse(string1);
long number2 = Int64.Parse(string1);
//and now do the math
long result = number1 - number2;


if you need bigger numbers, so must split the numbers from the right side.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900