Reverse last k digits of the given numberInput Format:Accept two integer as inputOutput Format:print the reversed k digits
Question
Reverse last k digits of the given number
Input Format:
Accept two integers as input
Output Format:
Print the reversed k digits
Solution
Here is a step-by-step solution in Python:
- First, we need to accept two integers as input. Let's call the first integer
numand the second integerk.
num = int(input("Enter the number: "))
k = int(input("Enter the number of digits to reverse: "))
- Next, we need to extract the last
kdigits fromnum. We can do this by convertingnumto a string, slicing the lastkcharacters, and then converting back to an integer.
last_k_digits = int(str(num)[-k:])
- Now, we need to reverse these
kdigits. We can do this by convertinglast_k_digitsto a string, reversing the string using slicing, and then converting back to an integer.
reversed_digits = int(str(last_k_digits)[::-1])
- Finally, we need to replace the last
kdigits ofnumwithreversed_digits. We can do this by subtractinglast_k_digitsfromnum, and then addingreversed_digits.
num = num - last_k_digits
num = num + reversed_digits
- Print the final result.
print("The number after reversing the last k digits is: ", num)
Please note that this solution assumes that num has at least k digits. If num has fewer than k digits, the program will reverse all the digits of num.
Similar Questions
Write a C++ program to find Reverse of a Number using class.inputEnter a number: 12345output54321
Write a program in C to print a string in reverse using a character pointer.Also print the uppercase of the first letter of the reversed word.
Input FormatThe first line of input consist of a Binary numberOutput FormatPrint the decimal equivalent for the given Binary number
Write a program to enter two numbers and print the arithmeticoperations like +,-,*,**, /, // and % using function
Write a program that takes a string of lowercase characters as input and prints it in uppercase, reversed.
Upgrade your grade with Knowee
Get personalized homework help. Review tough concepts in more detail, or go deeper into your topic by exploring other relevant questions.