Given an integer N, the task is to find the smallest number to be subtracted from N to obtain a palindrome.
Examples:
Input: N = 1000
Output: 1
Explanation: Since 1000 – 1 = 999, which is a palindrome, the smallest number to be subtracted is 1.
Input: N = 3456
Output: 13
Explanation: Since 3456 – 13 = 3443, which is a palindrome, the smallest number to be subtracted is 13.
Approach: Follow the steps below to solve the problem:
- Iterate from N to 0.
- Initialize a counter. At each iteration reverse the reduced value of N and compare it to the current value of N. If both are equal, print the value of the counter.
- Otherwise, increment the counter and continue the loop until N is 0.
- Print the value of the counter.
Below is the implementation of the above approach:
C++
#include <iostream>
using namespace std;
void minSub( int N)
{
int count = 0;
while (N >= 0) {
int num = N;
int rev = 0;
while (num != 0) {
int digit = num % 10;
rev = (rev * 10) + digit;
num = num / 10;
}
if (N == rev) {
break ;
}
count++;
N--;
}
cout << count;
}
int main()
{
int N = 3456;
minSub(N);
return 0;
}
|
Java
import java.util.*;
class GFG{
static void minSub( int N)
{
int count = 0 ;
while (N >= 0 )
{
int num = N;
int rev = 0 ;
while (num != 0 )
{
int digit = num % 10 ;
rev = (rev * 10 ) + digit;
num = num / 10 ;
}
if (N == rev)
{
break ;
}
count++;
N--;
}
System.out.print(count);
}
public static void main(String[] args)
{
int N = 3456 ;
minSub(N);
}
}
|
Python3
def minSub(N):
count = 0
while (N > = 0 ):
num = N
rev = 0
while (num ! = 0 ):
digit = num % 10
rev = (rev * 10 ) + digit
num = num / / 10
if (N = = rev):
break
count + = 1
N - = 1
print (count)
if __name__ = = '__main__' :
N = 3456
minSub(N)
|
C#
using System;
class GFG{
static void minSub( int N)
{
int count = 0;
while (N >= 0)
{
int num = N;
int rev = 0;
while (num != 0)
{
int digit = num % 10;
rev = (rev * 10) + digit;
num = num / 10;
}
if (N == rev)
{
break ;
}
count++;
N--;
}
Console.Write(count);
}
public static void Main(String[] args)
{
int N = 3456;
minSub(N);
}
}
|
Javascript
<script>
function minSub(N)
{
let count = 0;
while (N >= 0)
{
let num = N;
let rev = 0;
while (num != 0)
{
let digit = num % 10;
rev = (rev * 10) + digit;
num = Math.floor(num / 10);
}
if (N == rev)
{
break ;
}
count++;
N--;
}
document.write(count);
}
let N = 3456;
minSub(N);
</script>
|
Time Complexity: O(N * K), Where K is the number of digits of the integer.
Auxiliary Space: O(1)