Array ( [0] => [1] => questions [2] => Basic [3] => Swap-first-and-last-digit )
Given a integer N. You have to swap the first and last digit of given number and print the number.
First line contains a integer N.
Print the number after swapped.
132
231
2019
9012
588
885
Login to see Discussion
Approach 1: Convert to string
Step-i) convert the given number to string and store it in a variable
Step-ii) get length of the string
Step-iii)now swap the first and last characters of the string
Step-iv) return the string
Time Complexity: O(n) as there is copy of string to other string for returning purpose
Space Complexity: O(n)
Approach 2: Using Mathematic Operations
Step-i) get last digit by dividing the number with 10
Step-ii) get no of digits using log
Step-iii) get the first digit by dividing the number with 10 to the power of no of digits
Step-iv) multiply the last digit to 10 to the power of no of digits and then add the first digit
Step-v) for the above result add ( num - (first * Math.pow(10,digits) + last)))
Step-vi) return the result
Time Complexity: O(1)
Space Complexity: O(1)
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