Count of integers having difference with its reverse equal to D
Last Updated :
07 Mar, 2022
Given an integer D, the task is to find the count of all possible positive integers N such that reverse(N) = N + D.
Examples:
Input: D = 63
Output: 2
Explanation:
For N = 18, 18 + 63 = 81, which satisfies the condition N + D = reverse(N).
For N = 29, 29 + 63 = 92, which satisfies the condition N + D = reverse(N).
Therefore, the required output is 2
Input: D = 75
Output: 0
Approach: The problem can be solved based on the following observations:
N + D = reverse(N) => N - reverse(N) = D
=> D = ?(i=0 to [L/2]-1)(10L-1-i -10i )*( ni - nL-1-i), L = Count of digits in N.
If di = ni ? nL?1?i (0 ? i ? ?L/2? ? 1)
reverse(N) ? N = ?(i=0 to [L/2]-1) (10L-1-i -10i )*di
Follow the steps below to solve the problem:
- Let f(L, D) = reverse(N) ? N. Finding the count of N that satisfy the given formula is almost equivalent to enumerating the pairs of L and a sequence of integers in the range [?9, 9], { d0, d1, . . ., d?L/2??1 } (take into account that there is more than one N that corresponds to a sequence of di, though). Here, for any i such that 0 ? i < ?L/2? ? 1, the following holds:
10L?1?i ? 10i > ?(j=i+1 to [L/2 - 1]) ((10L?1?j ? 10j) · 9) + 10L??L/2?
- Let LD be the number of digits of D in decimal notation. Then, when L > 2LD and f(L, d) > 0, it can be seen that f(L, d) > D.
- Therefore, it is enough to consider the values between LD and 2LD as the value of L.
- For a fixed value of L, consider enumerating the sequences { d0, d1, ..., d?L/2??1 } such that f(L, d) = D (and finding the count of N that satisfy the given formula), by performing Depth First Search starting from d0.
- When the values up to di?1 are already decided, it can be seen that there are at most two candidates of the value of di that have to be considered: the maximum value such that (10i ? 10L?1?i )di ? dif , and the minimum value such that (10i ? 10L?1?i )di > dif . (Intuitively, if the “halfway” value of f(L, d) during the search gets too far from D, it is not possible to “get back”, and thus it should “stay close” to D.)
- Therefore, for a fixed value of L, find the count of N that satisfy the given formula in O(2?L/2?) time.
Below is the implementation of the above approach :
C++
// Cpp program for the
// above approach
#include <bits/stdc++.h>
using namespace std;
// Maximum digits in N
int MAXL = 17;
int N;
vector<int> v;
// Function to find count
// of possible values
// of N such that N + D = reverse(N)
int count(int D, int l, int t, int x[])
{
// Base Case
if (t == N) {
// If D is not equal to 0
if (D != 0)
return 0;
// Stores count of possible values
// of N such that N + D = reverse(N)
long ans = 1;
for (int i = 0; i < N; i++) {
// Update ans
ans *= (i == 0 ? 9 : 10) - abs(x[i]);
}
// If l is even
if (l % 2 == 0) {
// Update ans
ans *= 10;
}
return ans;
}
// Stores count of possible values
// of N such that N + D = reverse(N)
long ans = 0;
// Iterate over the range [-9, 9]
for (int m = -9; m <= 9; m++) {
if (-v[t] < D + v[t] * m && D +
v[t] * m < v[t]) {
x[t] = m;
// Update ans
ans += count(D + v[t] * m, l,
t + 1, x);
}
}
return ans;
}
// Utility function to find count of N
// such that N + D = reverse(N)
int findN(int D)
{
// If d is a multiple of 9,
// no such value N found
if (D % 9 != 0)
return 0;
// Divide D by 9 check reverse
// of number and its sum
D /= 9;
// B[i]: Stores power of (10, i)
vector<int> B(MAXL);
B[0] = 1;
// Calculate power(10, i)
for (int i = 1; i < MAXL; i++) {
// Update B[i]
B[i] = B[i - 1] * 10;
}
// Stores count of N such
// that N + D = reverse(N)
int ans = 0;
// Iterate over the range [1, MAXL]
for (int i = 1; i <= MAXL; i++) {
N = (i + 1) / 2;
v.clear();
v.resize(N);
for (int j = 0; j < N; j++)
for (int k = j; k < i - j; k++)
v[j] += B[k];
int arr[N];
ans += count(D, i, 0, arr);
}
return ans;
}
// Driver Code
int main()
{
int D = 63;
// Function call
cout << findN(D);
}
Java
// Java program of the above approach
import java.util.*;
public class Main {
// Maximum digits in N
static final int MAXL = 17;
static int N;
static long[] v;
// Utility function to find count of N
// such that N + D = reverse(N)
static long findN(int D)
{
// If d is a multiple of 9,
// no such value N found
if (D % 9 != 0)
return 0;
// Divide D by 9 check reverse
// of number and its sum
D /= 9;
// B[i]: Stores power of (10, i)
long[] B = new long[MAXL];
B[0] = 1;
// Calculate power(10, i)
for (int i = 1; i < MAXL; i++) {
// Update B[i]
B[i] = B[i - 1] * 10;
}
// Stores count of N such
// that N + D = reverse(N)
long ans = 0;
// Iterate over the range [1, MAXL]
for (int i = 1; i <= MAXL; i++) {
N = (i + 1) / 2;
v = new long[N];
for (int j = 0; j < N; j++)
for (int k = j; k < i - j; k++)
v[j] += B[k];
// Update ans
ans += count(D, i, 0, new int[N]);
}
return ans;
}
// Function to find count of possible values
// of N such that N + D = reverse(N)
static long count(long D, int l,
int t, int[] x)
{
// Base Case
if (t == N) {
// If D is not equal to 0
if (D != 0)
return 0;
// Stores count of possible values
// of N such that N + D = reverse(N)
long ans = 1;
for (int i = 0; i < N; i++) {
// Update ans
ans *= (i == 0 ? 9 : 10)
- Math.abs(x[i]);
}
// If l is even
if (l % 2 == 0) {
// Update ans
ans *= 10;
}
return ans;
}
// Stores count of possible values
// of N such that N + D = reverse(N)
long ans = 0;
// Iterate over the range [-9, 9]
for (int m = -9; m <= 9; m++) {
if (-v[t] < D + v[t] * m
&& D + v[t] * m < v[t]) {
x[t] = m;
// Update ans
ans += count(D + v[t] * m,
l, t + 1, x);
}
}
return ans;
}
// Driver Code
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
int D = 63;
// Function call
System.out.println(findN(D));
sc.close();
}
}
Python3
# Python program of the above approach
# Maximum digits in N
MAXL = 17;
N = 0;
v = 0;
# Utility function to find count of N
# such that N + D = reverse(N)
def findN(D):
global N;
global v;
# If d is a multiple of 9,
# no such value N found
if (D % 9 != 0):
return 0;
# Divide D by 9 check reverse
# of number and its sum
D //= 9;
# B[i]: Stores power of (10, i)
B = [0]*MAXL;
B[0] = 1;
# Calculate power(10, i)
for i in range(1, MAXL):
# Update B[i]
B[i] = B[i - 1] * 10;
# Stores count of N such
# that N + D = reverse(N)
ans = 0;
# Iterate over the range [1, MAXL]
for i in range(1, MAXL + 1):
N = (i + 1) // 2;
v = [0]*N;
for j in range(N):
for k in range(j, i - j):
v[j] += B[k];
# Update ans
temp = [0]*N;
ans += count(D, i, 0, temp);
return ans;
# Function to find count of possible values
# of N such that N + D = reverse(N)
def count(D, l, t, x):
global N;
global v;
# Base Case
if (t == N):
# If D is not equal to 0
if (D != 0):
return 0;
# Stores count of possible values
# of N such that N + D = reverse(N)
ans = 1;
for i in range(N):
# Update ans
ans *= (9 if i == 0 else 10) - abs(x[i]);
# If l is even
if (l % 2 == 0):
# Update ans
ans *= 10;
return ans;
# Stores count of possible values
# of N such that N + D = reverse(N)
ans = 0;
# Iterate over the range [-9, 9]
for m in range(-9, 10):
if (-v[t] < D + v[t] * m and D + v[t] * m < v[t]):
x[t] = m;
# Update ans
ans += count(D + v[t] * m, l, t + 1, x);
return ans;
# Driver Code
if __name__ == '__main__':
D = 63;
# Function call
print(findN(D));
# This code is contributed by 29AjayKumar
C#
// C# program for the above approach
using System;
class GFG
{
// Maximum digits in N
static int MAXL = 17;
static int N;
static long[] v;
// Utility function to find count of N
// such that N + D = reverse(N)
static long findN(int D)
{
// If d is a multiple of 9,
// no such value N found
if (D % 9 != 0)
return 0;
// Divide D by 9 check reverse
// of number and its sum
D /= 9;
// B[i]: Stores power of (10, i)
long[] B = new long[MAXL];
B[0] = 1;
// Calculate power(10, i)
for (int i = 1; i < MAXL; i++)
{
// Update B[i]
B[i] = B[i - 1] * 10;
}
// Stores count of N such
// that N + D = reverse(N)
long ans = 0;
// Iterate over the range [1, MAXL]
for (int i = 1; i <= MAXL; i++)
{
N = (i + 1) / 2;
v = new long[N];
for (int j = 0; j < N; j++)
for (int k = j; k < i - j; k++)
v[j] += B[k];
// Update ans
ans += count(D, i, 0, new int[N]);
}
return ans;
}
// Function to find count of possible values
// of N such that N + D = reverse(N)
static long count(long D, int l,
int t, int[] x)
{
// Base Case
if (t == N)
{
// If D is not equal to 0
if (D != 0)
return 0;
// Stores count of possible values
// of N such that N + D = reverse(N)
long ans = 1;
for (int i = 0; i < N; i++)
{
// Update ans
ans *= (i == 0 ? 9 : 10)
- Math.Abs(x[i]);
}
// If l is even
if (l % 2 == 0)
{
// Update ans
ans *= 10;
}
return ans;
}
// Stores count of possible values
// of N such that N + D = reverse(N)
long anss = 0;
// Iterate over the range [-9, 9]
for (int m = -9; m <= 9; m++)
{
if (-v[t] < D + v[t] * m
&& D + v[t] * m < v[t])
{
x[t] = m;
// Update ans
anss += count(D + v[t] * m,
l, t + 1, x);
}
}
return anss;
}
// Driver code
public static void Main(String[] args)
{
int D = 63;
// Function call
Console.WriteLine(findN(D));
}
}
// This code is contributed by code_hunt.
JavaScript
<script>
// javascript program of the above approach
// Maximum digits in N
let MAXL = 17;
let N;
let v = []
// Utility function to find count of N
// such that N + D = reverse(N)
function findN(D)
{
// If d is a multiple of 9,
// no such value N found
if (D % 9 != 0)
return 0;
// Divide D by 9 check reverse
// of number and its sum
D /= 9;
// B[i]: Stores power of (10, i)
let B = new Array(MAXL).fill(0);
B[0] = 1;
// Calculate power(10, i)
for (let i = 1; i < MAXL; i++) {
// Update B[i]
B[i] = B[i - 1] * 10;
}
// Stores count of N such
// that N + D = reverse(N)
let ans = 0;
// Iterate over the range [1, MAXL]
for (let i = 1; i <= MAXL; i++) {
N = Math.floor((i + 1) / 2);
v = new Array(N).fill(0);
for (let j = 0; j < N; j++)
for (let k = j; k < i - j; k++)
v[j] += B[k];
// Update ans
ans += count(D, i, 0, new Array(N));
}
return ans;
}
// Function to find count of possible values
// of N such that N + D = reverse(N)
function count(D, l, t, x)
{
// Base Case
if (t == N) {
// If D is not equal to 0
if (D != 0)
return 0;
// Stores count of possible values
// of N such that N + D = reverse(N)
let ans = 1;
for (let i = 0; i < N; i++) {
// Update ans
ans *= (i == 0 ? 9 : 10)
- Math.abs(x[i]);
}
// If l is even
if (l % 2 == 0) {
// Update ans
ans *= 10;
}
return ans;
}
// Stores count of possible values
// of N such that N + D = reverse(N)
let ans = 0;
// Iterate over the range [-9, 9]
for (let m = -9; m <= 9; m++)
{
if (-v[t] < D + v[t] * m
&& D + v[t] * m < v[t])
{
x[t] = m;
// Update ans
ans += count(D + v[t] * m,
l, t + 1, x);
}
}
return ans;
}
// Driver Code
let D = 63;
// Function call
document.write(findN(D));
// This code is contributed by target_2.
</script>
Time Complexity: O(2LD), where LD denotes the number of digits of D in decimal notation.
Auxiliary Space: O( LD)
Similar Reads
Python Tutorial - Learn Python Programming Language Python is one of the most popular programming languages. Itâs simple to use, packed with features and supported by a wide range of libraries and frameworks. Its clean syntax makes it beginner-friendly. It'sA high-level language, used in web development, data science, automation, AI and more.Known fo
10 min read
DSA Tutorial - Learn Data Structures and Algorithms DSA (Data Structures and Algorithms) is the study of organizing data efficiently using data structures like arrays, stacks, and trees, paired with step-by-step procedures (or algorithms) to solve problems effectively. Data structures manage how data is stored and accessed, while algorithms focus on
7 min read
Java Tutorial Java is a high-level, object-oriented programming language used to build web apps, mobile applications, and enterprise software systems. It is known for its Write Once, Run Anywhere capability, which means code written in Java can run on any device that supports the Java Virtual Machine (JVM).Java s
10 min read
Python Interview Questions and Answers Python is the most used language in top companies such as Intel, IBM, NASA, Pixar, Netflix, Facebook, JP Morgan Chase, Spotify and many more because of its simplicity and powerful libraries. To crack their Online Assessment and Interview Rounds as a Python developer, we need to master important Pyth
15+ min read
Java OOP(Object Oriented Programming) Concepts Java Object-Oriented Programming (OOPs) is a fundamental concept in Java that every developer must understand. It allows developers to structure code using classes and objects, making it more modular, reusable, and scalable.The core idea of OOPs is to bind data and the functions that operate on it,
13 min read
C++ Programming Language C++ is a computer programming language developed by Bjarne Stroustrup as an extension of the C language. It is known for is fast speed, low level memory management and is often taught as first programming language. It provides:Hands-on application of different programming concepts.Similar syntax to
5 min read
Java Interview Questions and Answers Java is one of the most popular programming languages in the world, known for its versatility, portability, and wide range of applications. Java is the most used language in top companies such as Uber, Airbnb, Google, Netflix, Instagram, Spotify, Amazon, and many more because of its features and per
15+ min read
C Programming Language Tutorial C is a general-purpose mid-level programming language developed by Dennis M. Ritchie at Bell Laboratories in 1972. It was initially used for the development of UNIX operating system, but it later became popular for a wide range of applications. Today, C remains one of the top three most widely used
5 min read
Quick Sort QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s
12 min read
Merge Sort - Data Structure and Algorithms Tutorials Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. Merge
14 min read