Smaller palindromic number closest to N
Given an integer N, the task is to find the closest palindromic number which is smaller than N.
Examples:
Input: N = 4000
Output: 3993
Explanation:
3993 is the closest palindromic number to N(= 4000) which is also smaller than N(= 4000). Therefore, 3993 is the required answer.
Input: N = 2889
Output: 2882
Approach: Follow the steps below to solve the problem:
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
bool checkPalindrome( int N)
{
int rev = 0;
int temp = N;
while (N != 0) {
rev = rev * 10
+ N % 10;
N = N / 10;
}
N = temp;
if (N == rev) {
return true ;
}
return false ;
}
int closestSmallerPalindrome( int N)
{
do {
N--;
} while (N >= 0
&& !checkPalindrome(N));
return N;
}
int main()
{
int N = 4000;
cout << closestSmallerPalindrome(N);
return 0;
}
|
Java
import java.util.*;
import java.lang.Math;
class GFG {
static boolean checkPalindrome( int N)
{
int rev = 0 ;
int temp = N;
while (N != 0 ) {
rev = rev * 10
+ N % 10 ;
N = N / 10 ;
}
N = temp;
if (N == rev) {
return true ;
}
return false ;
}
static int
closestSmallerPalindrome( int N)
{
do {
N--;
} while (N >= 0
&& !checkPalindrome(N));
return N;
}
public static void main(String[] args)
{
int N = 4000 ;
System.out.println(
closestSmallerPalindrome(N));
}
}
|
Python3
def checkPalindrome(N):
rev = 0
temp = N
while (N ! = 0 ):
rev = rev * 10 + N % 10
N = N / / 10
N = temp
if (N = = rev):
return True
return False
def closestSmallerPalindrome(N):
while N > = 0 and not checkPalindrome(N):
N - = 1
return N
if __name__ = = '__main__' :
N = 4000
print (closestSmallerPalindrome(N))
|
C#
using System;
class GFG{
static bool checkPalindrome( int N)
{
int rev = 0;
int temp = N;
while (N != 0)
{
rev = rev * 10 + N % 10;
N = N / 10;
}
N = temp;
if (N == rev)
{
return true ;
}
return false ;
}
static int closestSmallerPalindrome( int N)
{
do
{
N--;
} while (N >= 0 && !checkPalindrome(N));
return N;
}
public static void Main()
{
int N = 4000;
Console.WriteLine(closestSmallerPalindrome(N));
}
}
|
Javascript
<script>
function checkPalindrome(N)
{
let rev = 0;
let temp = N;
while (N != 0) {
rev = Math.floor(rev * 10
+ N % 10);
N = Math.floor( N / 10);
}
N = temp;
if (N == rev) {
return true ;
}
return false ;
}
function
closestSmallerPalindrome(N)
{
do {
N--;
} while (N >= 0
&& !checkPalindrome(N));
return N;
}
let N = 4000;
document.write(closestSmallerPalindrome(N));
</script>
|
Time Complexity: O(N * log10N)
Auxiliary Space: O(log10N)
Last Updated :
26 Apr, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...