给定整数N ,任务是查找所有N个数字的计数,以使num + Rev(num)= 10 N – 1
例子:
Input: N = 2
Output: 9
All possible numbers are
18 + 81 = 99
27 + 72 = 99
36 + 45 = 99
45 + 54 = 99
54 + 45 = 99
63 + 54 = 99
72 + 27 = 99
81 + 18 = 99
90 + 09 = 99
Input: N = 4
Output: 90
方法有2种情况:
如果n为奇数,则答案将为0。
Let n = 3 then num = d1d2d3 and rev(num) = d3d2d1
num + rev(num) should be 999 since n = 3.
So the below equations must be satisfied
d1 + d3 = 9 … (1)
d2 + d2 = 9 … (2)
d3 + d1 = 9 … (3)
Considering equation 2:
d2 + d2 = 9
2 * d2 = 9
d2 = 4.5 which is not possible because the digit of a number should always be a whole number.
Therefore If n is odd then answer will be 0.
如果n为偶数,则答案将为9 * 10 (N / 2 – 1) 。
Let n = 4 then num = d1d2d3d4 and rev(num) = d4d3d2d1
So the below equations should be satisfied
d1 + d4 = 9 … (1)
d2 + d3 = 9 … (2)
d3 + d2 = 9 … (3)
d4 + d1 = 9 … (4)
Considering equation 1: d1 + d4 = 9. It can be true in 9 ways:
(1 + 8), (2 + 7), (3 + 6), (4 + 5), (5 + 4), (6 + 3), (7 + 2), (8 + 1) and (9 + 0)
Similarly other equations will also have 9 solutions + 1 more solution since the remaining digits are not the first and last digit of the number and we can take sum of the form (0 + 9).
And since half of the equations are same
Therefore, if n is even then answer will be 9 * 10(N / 2 – 1).
下面是上述方法的实现
C++
// C++ implementation of the approach
#include
using namespace std;
// Function to return the
// count of such numbers
int countNumbers(int n)
{
// If n is odd
if (n % 2 == 1)
return 0;
return (9 * pow(10, n / 2 - 1));
}
// Driver code
int main()
{
int n = 2;
cout << countNumbers(n);
return 0;
}
Java
// Java implementation of the approach
class GFG {
// Function to return the
// count of such numbers
static int countNumbers(int n)
{
// If n is odd
if (n % 2 == 1)
return 0;
return (9 * (int)Math.pow(10, n / 2 - 1));
}
// Driver code
public static void main(String args[])
{
int n = 2;
System.out.print(countNumbers(n));
}
}
Python3
# Python3 implementation of the approach
# Function to return the
# count of such numbers
def countNumbers(n):
# If n is odd
if n % 2 == 1:
return 0
return (9 * pow(10, n // 2 - 1))
# Driver code
if __name__ == "__main__":
n = 2
print(countNumbers(n))
# This code is contributed
# by Rituraj Jain
C#
// C# implementation of the approach
using System;
class GFG {
// Function to return the
// count of such numbers
static int countNumbers(int n)
{
// If n is odd
if (n % 2 == 1)
return 0;
return (9 * (int)Math.Pow(10, n / 2 - 1));
}
// Driver code
public static void Main()
{
int n = 2;
Console.WriteLine(countNumbers(n));
}
}
PHP
Javascript
9
时间复杂度: O(1)