Close
Close

what is the logic used in print a new number with digits reversed as of original ? i'm little confused with the solution

   vinodhini

can you please explain the below code?

print "Enter number"
number = input()

#seperating digits of the number
#1234/1000 = 1
#1234%1000 = 234

first_number = number/1000
rem = number%1000

#234/100 = 2
#234%100 = 34
second_number = rem/100
rem = rem%100

#34/10 = 3
#34%10 = 4
third_number = rem/10
fourth_number = rem%10

#creating new number with digits reversed
#1234 = (1*1000)+(2*100)+(3*10)+4 i.e., 1000+200+30+4
new_number = (fourth_number*1000)+(third_number*100)+(second_number*10)+(first_number)
print new_number

  • number = input('Enter a Number: ') a=number/1000 b=(number-(a*1000))/100 c=(number-(a*1000)-(b*100))/10 d=(number-(a*1000)-(b*100)-(c*10))/1 print (1000*d)+(100*c)+(10*b)+(1*a)
    - Jwala

Answers

  •   
    first_number = number/1000
    rem = number%1000

    We are just extracting the first digit of the number here. For example, if the number is 1234, then 1234/1000 will give 1. So, now we have the first digit of the number. number%1000 will give us (1234%1000) 234 i.e., the rest of the number without the first digit.

    So, now we have the first digit. So, we will extract the first digit of the new number (234) in the same way and this will be the second digit of the number.

    So, 234/100 will give us 2.

    Thus, now we have 1 and 2. Similarly, we will get 3 and 4 also.

    The last step is just to form a new number with the digits reversed. i.e, (4*1000)+(3*100)+(2*10)+(1*1) = 4321.



  •   

    number = input('Enter a Number: ')
    a=number/1000
    b=(number-(a*1000))/100
    c=(number-(a*1000)-(b*100))/10
    d=(number-(a*1000)-(b*100)-(c*10))/1
    print (1000*d)+(100*c)+(10*b)+(1*a)
        




     


    • sorry!! you may not understand my comment to your question
      - Jwala

  •    emmausa

    This is one of the best articles I have ever read on this blog. Thank you for sharing very interesting information. slope



  •    seoexpertim

    MaroCar is cheap car rental service in Morocco that will allow you to rent a quality car with affordable pricein just a few clicks. The platform offers a wide choice of cars at affordable prices allowing you to make considerable savings. sd hang tuah 6 surabaya



Ask Yours
Post Yours
Write your answer