Last Updated on March 28, 2022 by Ria Pathak
CONCEPTS USED:
Recursion
DIFFICULTY LEVEL:
Easy
PROBLEM STATEMENT(SIMPLIFIED):
Given a number N, check whether the number is palindrome or not using recursion. The palindrome number remains the same when its digits are reversed.
See original problem statement here
For Example :
Input : N = "12321"
Output : YES
Input : N = "123"
Output : NO
Explanation : 123 is not equal to 321
SOLVING APPROACH:
-
Find
reverse
of a number –
1.1 Initialiseresult
with 0.
1.2 Whenever value of N becomes 0, returnresult
.
1.3 If N is not 0, updateresult
withresult
* 10 + N%10.
1.4 And recursively solve for N/10. -
Compare
reverse
with N if both are equal, print YES else NO.
ALGORITHM:
result = 0
solve(N) :
if(N becomes 0)
return result
else
res = res * 10 + N %10
solve(N/10)
SOLUTIONS:
#include <stdio.h> //function for finding reverse of a number int isPalin(int n,int res){ if(n == 0) return res; res = res*10 + n%10; return isPalin(n/10,res); } int main() { int t; scanf("%d",&t); while(t--){ int n; scanf("%d",&n); int rev = isPalin(n,0); if(n == rev) printf("YES\n"); else printf("NO\n"); } return 0; }
#include <bits/stdc++.h> using namespace std; //function for finding reverse of a number int isPalin(int n,int res){ if(n == 0) return res; res = res*10 + n%10; return isPalin(n/10,res); } int main() { int t;cin>>t; while(t--){ int n;cin>>n; int rev = isPalin(n,0); if(n == rev) cout<<"YES\n"; else cout<<"NO\n"; } return 0; }
import java.util.*; import java.io.*; public class Main { //function for finding reverse of a number static int isPalin(int n,int res){ if(n == 0) return res; res = res*10 + n%10; return isPalin(n/10,res); } public static void main(String args[]) throws IOException { Scanner sc = new Scanner(System.in); int t = sc.nextInt(); while(t != 0){ int n = sc.nextInt(); int res = 0; int rev = isPalin(n,res); if(n == rev) System.out.println("YES"); else System.out.println("NO"); t--; } } }
def isPalin( n, res): if(n == 0): return res res = res * 10 + n % 10 return isPalin(n // 10, res) for _ in range(int(input())): n = int(input()) rev = isPalin(n, 0) if n == rev: print("YES") else: print("NO")
[forminator_quiz id="996"]
This article tried to discuss the Recursion. Hope this blog helps you understand the concept. To practice more problems on Recursion you can check out MYCODE | Competitive Programming