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]

### Like this:

Like Loading...

*Related*

## Published by Shahab

Completed B.Sc in CSE, @United International University, Dhaka.
Currently working as Development Engineer, Android and iOS Application.
View all posts by Shahab