Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding Reversed Numbers in python

I am solving SPOJ -ADDREV problem in short the question is :

Reversed number is For example, 1245 becomes 5421 and 2314 becomes 4132 .

Note that all the leading zeros are omitted. That means if the number ends with a zero, the zero is lost by reversing (e.g. 1200 gives 21).
Your task is to add two reversed numbers and output their reversed sum.

Of course, the result is not unique because any particular number is a reversed form of several numbers (e.g. 21 could be 12, 120 or 1200 before reversing). Thus we must assume that no zeros were lost by reversing (e.g. assume that the original number was 12).

Input

The input consists of N cases (equal to about 10000). The first line of the input contains only positive integer N. Then follow the cases. Each case consists of exactly one line with two positive integers separated by space. These are the reversed numbers you are to add.

Output

For each case, print exactly one line containing only one integer - the reversed sum of two reversed numbers. Omit any leading zeros in the output.

Example

Sample input:

3
24 1
4358 754
305 794

Sample output:

34
1998
1

my code is :

ctr=0
up=raw_input()
tocal=raw_input()
while ctr!=int(up):
    l=tocal.split(' ')
    num1=int(str(l[0])[::-1])
    num2=int(str(l[1])[::-1])
    while num1%10 ==0 or num2%10==0:
        if num1%10==0:
            num1=num1[:-1]
        elif num2%10==0:
            num2=num2[:-1]


    sum=int(num1)+int(num2)

    rsum=int(str(sum)[::-1])

    print rsum
    ctr+=1
    tocal=raw_input()

while testing in SPOJ it returned Runtime error and in ideone it shows

Traceback (most recent call last):
File "prog.py", line 2, in <module>
EOFError: EOF when reading a line

I checked my code on my pc and the results were correct I don't know what is happening here (I am new to SPOJ and may not know ways of writing code for these type of sites) unlike here and here I have not written any code within raw_input() then what is happening?

Also my code runs 1 more than desired call(i.e the raw_input() call) And I have not found any way to fix it .

like image 540
sid597 Avatar asked Sep 06 '25 05:09

sid597


1 Answers

I think this can be much more simple:

n1 = 754
n2 = 4358
print(int(str(int(str(n1)[::-1]) + int(str(n2)[::-1]))[::-1]))

Core:

int(str(n1)[::-1]) # convert integer to string, reverse string, convert string to integer

You have to do this 2x, once for each integer, then sum, then convert to string, reverse, and back to int.

The 'int' function will automatically strip the leading zeros

like image 195
philshem Avatar answered Sep 07 '25 20:09

philshem