KMon
KMon

Reputation: 1

function that reverses digits, takes into consideration the sign

I've looked on the site to try and figure out how to do this but I'm still stuck.

My function is supposed to reverse digits, so reverse_digits(8765) returns 5678. This is easily done by :

def reverse_digits(num):
    return int(str(num)[::-1])

However, my code needs to 1) test if it is a negative and keep it negative (so -8765 returns -5678) and 2) I think I should test to see if num is actually an int.

So far I have

def reverse_digits(num):
   num = str(num)[::-1]
   if num == '-':
       minus = 1
       num = num[:-1]
   else: 
       minus = 0    
   int(num)  
   if minus == 1:
       num = num*-1
   else:
       num = num   
   return num

It works for digits without a '-', but returns '' when it has a '-'.

I was originally trying to put the test to see if it is an int at the beginning od the loop like

if (num != int):
    print("wrong type") 
    sys.exit()
else:
   (the rest of my above code)

but that wouldn't work for me. Should I put all the code in a while loop so I can use continue/break? Thanks!

Upvotes: 0

Views: 72

Answers (2)

Daniel
Daniel

Reputation: 42748

Just don't put the - into the reversed string:

def reverse_digits(num):
    return (-1 if num<0 else 1) * int(str(abs(num))[::-1])

Upvotes: 4

Nf4r
Nf4r

Reputation: 1410

Try to use the isdigit() string method.

def reverse_digit(num):
      num_str = str(num)[::-1].strip('-')
      if not num_str.isdigit():
           <do what u want>
      if num < 0:
         return -int(num_str)
      else:
         return int(num_str)

Upvotes: 2

Related Questions