Skip to content
Related Articles

Related Articles

Find a number such that sum of N with it is a Palindrome

View Discussion
Improve Article
Save Article
  • Last Updated : 08 Aug, 2022

Given a very large number N, [1 ≤ length of digit of N (n) ≤ 106], the task is to find some positive integer of the same length as N without leading zeroes, such that the sum of these two numbers is a palindrome.

Examples:

Input: N = 54321
Output: 45678
Explanation: 54321 + 45678 = 99999 which is a palindrome.

Input: N = 999
Output: 112

 

Approach: To solve the problem follow the below idea:

If the number does not start with 9, then make the palindrome of  9999…… of length of N and if the number starts with 9 then make the palindrome 1111….. of length of (n + 1).

  • So, the resultant number if it does not starts with 9 is (9999….. to n – N). 
  • And, the resultant number if it starts with 9 is (11111….. to n+1 – N). 

Follow the below steps to solve the problem:

  • Find the number of digits present in N.
  • If N starts with 9:
    • Then consider the sum to be [1111…to (n+1)].
    • Then calculate the number as mentioned above.
  • If N does not start with 9:
    • Then consider the sum to be [999…to n].
    • Get the number following the process mentioned above.

Below is the implementation of the above approach:

C++




// C++ code to implement the above approach
 
#include <bits/stdc++.h>
using namespace std;
#define ll long long
 
// Function to find difference
// of two large strings
string findDiff(string str1, string str2)
{
    // Take an empty string for storing result
    string str = "";
 
    // Calculate length of both string
    int n1 = str1.length(), n2 = str2.length();
 
    // Reverse both of strings
    reverse(str1.begin(), str1.end());
    reverse(str2.begin(), str2.end());
 
    int carry = 0;
 
    // Run loop till small string length
    // and subtract digit of str1 to str2
    for (int i = 0; i < n2; i++) {
        int sub
            = ((str1[i] - '0') - (str2[i] - '0') - carry);
 
        // If subtraction is less then zero
        // then we 10 into sub and
        // take carry as 1 for calculating
        // next step
        if (sub < 0) {
            sub = sub + 10;
            carry = 1;
        }
        else
            carry = 0;
 
        str.push_back(sub + '0');
    }
 
    // Subtract remaining digits of
    // larger number
    for (int i = n2; i < n1; i++) {
        int sub = ((str1[i] - '0') - carry);
 
        // If the sub value is -ve,
        // then make it positive
        if (sub < 0) {
            sub = sub + 10;
            carry = 1;
        }
        else
            carry = 0;
    }
 
    // Reverse resultant string
    reverse(str.begin(), str.end());
    return str;
}
 
// Function to find the number which adds up
// to N makes the resultant number palindrome
string findPalin(string N)
{
    // Initialize variables
    ll n = N.size();
    string str = "";
 
    // If string starts with 9
    if (N[0] == '9') {
        while (n--) {
            str += '1';
        }
        str += '1';
        return findDiff(str, N);
    }
 
    // If string doesn't start with 9
    else {
        for (ll i = 0; i < n; i++) {
            str += ((9 - (N[i] - '0')) + '0');
        }
        return str;
    }
}
 
// Driver Code
int main()
{
    string N = "54321";
 
    // Function Call
    cout << findPalin(N);
    return 0;
}


Java




// Java code to implement the above approach
 
 
import java.util.*;
 
class GFG{
 
// Function to find difference
// of two large Strings
static String findDiff(String str1, String str2)
{
    // Take an empty String for storing result
    String str = "";
 
    // Calculate length of both String
    int n1 = str1.length(), n2 = str2.length();
 
    // Reverse both of Strings
    str1 = reverse(str1);
    str2 = reverse(str2);
 
    int carry = 0;
 
    // Run loop till small String length
    // and subtract digit of str1 to str2
    for (int i = 0; i < n2; i++) {
        int sub
            = ((str1.charAt(i) - '0') - (str2.charAt(i) - '0') - carry);
 
        // If subtraction is less then zero
        // then we 10 into sub and
        // take carry as 1 for calculating
        // next step
        if (sub < 0) {
            sub = sub + 10;
            carry = 1;
        }
        else
            carry = 0;
 
        str+=(sub + '0');
    }
 
    // Subtract remaining digits of
    // larger number
    for (int i = n2; i < n1; i++) {
        int sub = ((str1.charAt(i) - '0') - carry);
 
        // If the sub value is -ve,
        // then make it positive
        if (sub < 0) {
            sub = sub + 10;
            carry = 1;
        }
        else
            carry = 0;
    }
 
    // Reverse resultant String
    str = reverse(str);
    return str;
}
 
// Function to find the number which adds up
// to N makes the resultant number palindrome
static String findPalin(String N)
{
    // Initialize variables
    long n = N.length();
    String str = "";
 
    // If String starts with 9
    if (N.charAt(0) == '9') {
        while (n-- >0) {
            str += '1';
        }
        str += '1';
        return findDiff(str, N);
    }
 
    // If String doesn't start with 9
    else {
        for (int i = 0; i < n; i++) {
            str += String.valueOf(9 - Integer.parseInt(String.valueOf(N.charAt(i))));
        }
        return str;
    }
}
static String reverse(String input) {
    char[] a = input.toCharArray();
    int l, r = a.length - 1;
    for (l = 0; l < r; l++, r--) {
        char temp = a[l];
        a[l] = a[r];
        a[r] = temp;
    }
    return String.valueOf(a);
}
// Driver Code
public static void main(String[] args)
{
    String N = "54321";
 
    // Function Call
    System.out.print(findPalin(N));
}
}
 
// This code contributed by shikhasingrajput


Python3




# Python3 code to implement the above approach
 
# Function to find difference
# of two large strings
def findDiff(str1, str2):
    # Take an empty string for storing result
    str_ = ""
 
    # Calculate length of both string
    n1 = len(str1)
    n2 = len(str2)
 
    # Reverse both of strings
    str1 = str1[::-1]
    str2 = str2[::-1]
 
    carry = 0
 
    # Run loop till small string length
    # and subtract digit of str1 to str2
    for i in range(n2):
        sub = (int(str1[i]) - int(str2[i]) - carry)
 
        # If subtraction is less then zero
        # then we 10 into sub and
        # take carry as 1 for calculating
        # next step
        if (sub < 0):
            sub = sub + 10
            carry = 1
 
        else:
            carry = 0
 
        str_ += str_(sub)
 
    # Subtract remaining digits of
    # larger number
    for i in range(n2, n1):
        sub = int(str1[i]) - carry
 
        # If the sub value is -ve,
        # then make it positive
        if (sub < 0):
            sub = sub + 10
            carry = 1
 
        else:
            carry = 0
 
    # Reverse resultant string
    str_ = str_[::-1]
    return str_
 
# Function to find the number which adds up
# to N makes the resultant number palindrome
def findPalin(N):
    # Initialize variables
    n = len(N)
    str_ = ""
 
    # If string starts with 9
    if (N[0] == '9'):
        while n:
            str_ += '1'
            n -= 1
 
        str_ += '1'
        return findDiff(str_, N)
 
    # If string doesn't start with 9
    else:
        for i in range(n):
            str_ += str(9 - int(N[i]))
 
        return str_
 
# Driver Code
N = "54321"
 
# Function Call
print(findPalin(N))
 
# This code is contributed by phasing17


C#




// C# program to of the above approach
using System;
class GFG {
 
// Function to find difference
// of two large Strings
static string findDiff(string str1, string str2)
{
    // Take an empty String for storing result
    string str = "";
 
    // Calculate length of both String
    int n1 = str1.Length, n2 = str2.Length;
 
    // Reverse both of Strings
    str1 = reverse(str1);
    str2 = reverse(str2);
 
    int carry = 0;
 
    // Run loop till small String length
    // and subtract digit of str1 to str2
    for (int i = 0; i < n2; i++) {
        int sub
            = ((str1[i] - '0') - (str2[i] - '0') - carry);
 
        // If subtraction is less then zero
        // then we 10 into sub and
        // take carry as 1 for calculating
        // next step
        if (sub < 0) {
            sub = sub + 10;
            carry = 1;
        }
        else
            carry = 0;
 
        str+=(sub + '0');
    }
 
    // Subtract remaining digits of
    // larger number
    for (int i = n2; i < n1; i++) {
        int sub = ((str1[i] - '0') - carry);
 
        // If the sub value is -ve,
        // then make it positive
        if (sub < 0) {
            sub = sub + 10;
            carry = 1;
        }
        else
            carry = 0;
    }
 
    // Reverse resultant String
    str = reverse(str);
    return str;
}
 
// Function to find the number which adds up
// to N makes the resultant number palindrome
static string findPalin(string N)
{
    // Initialize variables
    long n = N.Length;
    string str = "";
 
    // If String starts with 9
    if (N[0] == '9') {
        while (n-- >0) {
            str += '1';
        }
        str += '1';
        return findDiff(str, N);
    }
 
    // If String doesn't start with 9
    else {
        for (int i = 0; i < n; i++) {
            str += (9 - Int32.Parse(N[i].ToString())).ToString();
        }
        return str;
    }
}
static string reverse(string input) {
    char[] a = input.ToCharArray();
    int l, r = a.Length - 1;
    for (l = 0; l < r; l++, r--) {
        char temp = a[l];
        a[l] = a[r];
        a[r] = temp;
    }
    return a.ToString();
}
   
// Driver Code
public static void Main()
{
    string N = "54321";
 
    // Function Call
   Console.Write(findPalin(N));
}
}
 
// This code is contributed by sanjoy_62.


Javascript




<script>
 
// JavaScript code to implement the above approach
 
// Function to find difference
// of two large strings
function findDiff(str1, str2)
{
    // Take an empty string for storing result
    let str = "";
 
    // Calculate length of both string
    let n1 = str1.length, n2 = str2.length;
 
    // Reverse both of strings
    str1 = str1.split("").reverse().join("");
    str2 = str2.split("").reverse().join("");
 
    let carry = 0;
 
    // Run loop till small string length
    // and subtract digit of str1 to str2
    for (let i = 0; i < n2; i++) {
        let sub
            = ((str1[i] - '0') - (str2[i] - '0') - carry);
 
        // If subtraction is less then zero
        // then we 10 into sub and
        // take carry as 1 for calculating
        // next step
        if (sub < 0) {
            sub = sub + 10;
            carry = 1;
        }
        else
            carry = 0;
 
        str += sub.toString();
    }
 
    // Subtract remaining digits of
    // larger number
    for (let i = n2; i < n1; i++) {
        let sub = ((str1.charCodeAt(i) - '0'.charCodeAt(0)) - carry);
 
        // If the sub value is -ve,
        // then make it positive
        if (sub < 0) {
            sub = sub + 10;
            carry = 1;
        }
        else
            carry = 0;
    }
 
    // Reverse resultant string
    str = str.split().reverse().join("");
    return str;
}
 
// Function to find the number which adds up
// to N makes the resultant number palindrome
function findPalin(N)
{
    // Initialize variables
    let n = N.length;
    let str = "";
 
    // If string starts with 9
    if (N[0] == '9') {
        while (n--) {
            str += '1';
        }
        str += '1';
        return findDiff(str, N);
    }
 
    // If string doesn't start with 9
    else {
        for (let i = 0; i < n; i++) {
            str += (9 - parseInt(N[i])).toString();
        }
        return str;
    }
}
 
// Driver Code
let N = "54321";
 
// Function Call
document.write(findPalin(N),"</br>");
 
// This code is contributed by shinjanpatra
 
</script>


Output

45678

Time Complexity: O(N)
Auxiliary Space: O(N)


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!