In: Computer Science
Solving Problems Using Recursion (Python):
To solve the problem, you have to use recursion and cannot use for or while loops to solve the problems as well as not using global variables.
1. Create a function that takes a positive integer and returns it with neighboring digits removed. Do not convert the integer to a list.
Ex.
Input = [5555537777721]
Output = [53721]
#function which takes an integer and returns it with neighboring
digits removes using recursion
def func(num):
#base case
#check if num is a single digit number
x=num//10
#if num is a single digit number then return it.
if x==0:
return num
#otherwise check if the last two digits are the same
rem1=num%10
num=num//10
rem2=num%10
#if last two digit are same then call func() with last digit
removed recursively
if rem1==rem2:
return func(num)
#otherwise call func() with last digit removed but add the last
digit in the returned answer
else:
return func(num)*10+rem1
#take input integer
num=int(input())
#print the result returned by the function
print(func(num))
5555537777721 53721
11112226666343453300 1263434530
CODE and INPUT/OUTPUT
So if you have any doubt regarding this solution please feel free to ask in the comment section below and if it is helpful then please upvote this solution, THANK YOU.