Check whether the number can be made palindromic after adding K
Last Updated :
24 Nov, 2021
Given two numbers N and K, the task is to check whether the given number N can be made a palindromic after adding K to it.
Example:
Input: N = 19, K = 3
Output: Yes
Explanation:
19 + 3 = 22 and 22 is a palindrome.
Input: N = 15, K = 3
Output: No
Explanation:
15 + 3 = 18 and 18 is not a palindrome.
Approach: The idea is to first add K to the given number and then check if the obtained number is a palindrome or not.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
void checkPalindrome( int num)
{
string str = to_string(num);
int l = 0, r = str.length() - 1;
while (l < r) {
if (str[l] != str[r]) {
cout << "No" ;
return ;
}
l++;
r--;
}
cout << "Yes" ;
return ;
}
int main()
{
int n = 19, k = 3;
checkPalindrome(n + k);
return 0;
}
|
Java
import java.util.*;
class GFG{
static void checkPalindrome( int num)
{
String str = Integer.toString(num);
int l = 0 , r = str.length() - 1 ;
while (l < r) {
if (str.charAt(l) != str.charAt(r)) {
System.out.print( "No" );
return ;
}
l++;
r--;
}
System.out.print( "Yes" );
return ;
}
public static void main(String args[])
{
int n = 19 , k = 3 ;
checkPalindrome(n + k);
}
}
|
Python3
def checkPalindrome(num):
string = str (num)
l = 0
r = len (string) - 1 ;
while (l < r):
if (string[l] ! = string[r]) :
print ( "No" )
return ;
l = l + 1 ;
r = r - 1 ;
print ( "Yes" )
return ;
if __name__ = = '__main__' :
n = 19
k = 3
checkPalindrome(n + k);
|
C#
using System;
class GFG{
static void checkPalindrome( int num)
{
String str = num.ToString();
int l = 0, r = str.Length - 1;
while (l < r) {
if (str[l] != str[r]) {
Console.Write( "No" );
return ;
}
l++;
r--;
}
Console.Write( "Yes" );
return ;
}
public static void Main(String []args)
{
int n = 19, k = 3;
checkPalindrome(n + k);
}
}
|
Javascript
<script>
function checkPalindrome(num)
{
let str = num.toString();
let l = 0, r = str.length - 1;
while (l < r) {
if (str[l] != str[r]) {
document.write( "No" );
return ;
}
l++;
r--;
}
document.write( "Yes" );
return ;
}
let n = 19, k = 3;
checkPalindrome(n + k);
</script>
|
Time Complexity: O(n)
Auxiliary Space: O(1)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...