Check if number is palindrome or not in base B
Last Updated :
17 Mar, 2021
Given an integer N, the task is to check if
(N in base B) is palindrome or not.
Examples:
Input: N = 5, B = 2
Output: Yes
Explanation:
(5)10 = (101)2 which is palindrome. Therefore, the required output is Yes.
Input: N = 4, B = 2
Output: No
Approach: The problem can be solved by checking if the decimal value of the reverse of
is equal to N or not. Follow the steps below to solve the problem.
- Initialize the variable, rev = 0 to store the reverse of N.
- Extract the digits of
- by N % B.
- For each digit of
- Update rev= rev * B + N % B
- Finally, check if N is equal to rev or not
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int checkPalindromeB( int N, int B)
{
int rev = 0;
int N1 = N;
while (N1) {
rev = rev * B + N1 % B;
N1 = N1 / B;
}
return N == rev;
}
int main()
{
int N = 5, B = 2;
if (checkPalindromeB(N, B)) {
cout << "Yes" ;
}
else {
cout << "No" ;
}
}
|
Java
class GFG{
static boolean checkPalindromeB( int N,
int B)
{
int rev = 0 ;
int N1 = N;
while (N1 > 0 )
{
rev = rev * B + N1 % B;
N1 = N1 / B;
}
return N == rev;
}
public static void main(String[] args)
{
int N = 5 , B = 2 ;
if (checkPalindromeB(N, B))
{
System.out.print( "Yes" );
}
else
{
System.out.print( "No" );
}
}
}
|
Python3
def checkPalindromeB(N, B):
rev = 0 ;
N1 = N;
while (N1 > 0 ):
rev = rev * B + N1 % B;
N1 = N1 / / B;
return N = = rev;
if __name__ = = '__main__' :
N = 5 ; B = 2 ;
if (checkPalindromeB(N, B)):
print ( "Yes" );
else :
print ( "No" );
|
C#
using System;
class GFG{
static bool checkPalindromeB( int N,
int B)
{
int rev = 0;
int N1 = N;
while (N1 > 0)
{
rev = rev * B + N1 % B;
N1 = N1 / B;
}
return N == rev;
}
public static void Main(String[] args)
{
int N = 5, B = 2;
if (checkPalindromeB(N, B))
{
Console.Write( "Yes" );
}
else
{
Console.Write( "No" );
}
}
}
|
Javascript
<script>
function checkPalindromeB(N, B)
{
var rev = 0;
var N1 = N;
while (N1) {
rev = rev * B + N1 % B;
N1 = parseInt(N1 / B);
}
return N == rev;
}
var N = 5, B = 2;
if (checkPalindromeB(N, B)) {
document.write( "Yes" );
}
else {
document.write( "No" );
}
</script>
|
Time Complexity:O(logBN)
Auxiliary Space:O(1)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...