Acm (UVa) : 713


Adding Reversed Number

Data type:
Character / String

// Critical Case:
After reversing a number, if there are preceding 0
Let, a number: 85210000, Reversed: 1258
After adding two number, if there r preceding 0 before result
Let, result = 0001, so the output will be: 1

// Technique:
This problem can be solved by without reversing anything
Start addition form Left most digit and move to right and pass the carry to the right.
Still u have to be very careful abt the critical cases.

Critical Input:
4
0005 36
9999 1111
1000 0001
963 369

Critical Output:
3605
1111
1001
2331

// Uva online Judge: ACM problem no: 713
// Author: Tausiq >>> CTE, UIU >>> Bangladesh.

#include
#include

int main ()
{
long N, Len, I, LenA, LenB, Carry, Sum[210], X;
char A [210], B [210], Temp [210];

scanf(“%ld”, &N);

while ( N ){

// Initialize with 0
for ( I = 0; I < 210; I++) A [I] = B [I] = 48; // Trim the former 0's of 1st number scanf("%s", Temp); Len = strlen ( Temp ); while ( Temp [ Len-1 ] == '0' ) Len--; LenA = 0; for ( I = 0; I < Len; I++) A [LenA++] = Temp [I]; // Similarly from 2nd number scanf("%s", Temp); Len = strlen ( Temp ); while ( Temp [ Len-1 ]== '0') Len--; LenB = 0; for ( I = 0; I < Len; I++) B [LenB++] = Temp [I]; Len = LenA > LenB ? LenA : LenB; // Highest length

// Addition
Carry = X = 0;
for ( I = 0; I < Len; I++){ Carry = ( A [I] - 48 ) + ( B [I] - 48 ) + Carry; Sum [X++] = Carry % 10; //printf("%d", Carry%10); Carry /= 10; } while ( Carry != 0 ){ // if Carry is carrying sth Sum [X++] = Carry % 10; //printf("%d", Carry%10); Carry /= 10; } // cross out precedence 0 I = 0; while ( Sum [I] == 0) I++; // output while ( I < X ) printf("%d", Sum[I++]); printf("\n"); N--; } return 0; } [/sourcecode]

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s