Array ( [0] => [1] => questions [2] => Basic [3] => Reversing-the-Number )
Given a integer N. You have to reverse the given number and print it.
First line contains a integer N.
Print the reversed number.
589
985
7893444
4443987
11267
76211
Login to see Discussion
Approach 1: using while loop
Step-i) initialize a reverse variable to zero
Step-ii) get the remainder of the given number after dividing with 10
Step-iii) multiply reverse with 10 and add remainder to it
Step-iv)repeat step ii and iii till the number is greater than 0
Step-v) return the reverse variable
Time Complexity: O(n)
Space Complexity: O(1)
Approach 2: using recursion
Step-i) create two static variable reverse, position and initialize them with 0 and 1 respectively
Step-ii) if num > 0 call the present function by passing num/10 as parameter
Step-iii) add the value of (number %10) * position to the reverse variable
Step-iv)multiply position value to 10
Step-v) return reverse
Time Complexity: O(n)
Space Complexity: O(1)
Approach 3: By converting the given number to string
Step-i)convert the given number to string and store it in a variable
Step-ii)reverse the string
Step-iii) return the string
Time Complexity: O(n)
Space Complexity: O(n)
Note :
Let us know if you can come up with a better approach, mail us at support@theinquisitive.in Your approach will be reviewed and posted with credits to you.
Login to see Solution