Friday, October 30, 2009

How to handle very large test cases in c++

Most of us come across some c++ problems where we are asked to get some simple calculations done. For example: we can get a problem of subtracting 1 from a 100 digit number. Now, subtracting one is not a big problem for us but the problem is '100 digit number'.

None of the datatype has capacity to store such a large number. Stop thinking about unsigned long long.. even it cant..!! So, here's a short solution to this cute problemo..

We can take the input as a string and process each of its elements as in elementary mathematics i.e. if last digit is'nt 0 then reduce it by 1(dont forget it to convert to int and then back to string).. if last digit is zero then make it nine and move back to the adjacent digit following the same procedure. Simple :)

Here's the source code..

#include
using namespace std;
int main()
{
int i,t=40;
string z;
cin>>z;
i=z.size()-1;
do
{
if(z[i]!='0')
{
z[i]=int(z[i])-1;
break;
}
z[i--]=57;

}while(i>=0);
Then print the string a.

The only problem comes when we give input as 10, 100, 1000, 10000 ... the answer comes out as 09, 099, 0999, 09999... instead of normal numbers such as.. 9, 99, 999, 9999... I have resolved this problem for myself.. I'll not upload the source.. try it out yourself..!! ;)

* * * * *

No comments:

Post a Comment