给定整数N≥1 ,任务是找到两个N位数字的最小和最大和。
例子:
Input: N = 1
Output:
Largest = 18
Smallest = 0
Largest 1-digit number is 9 and 9 + 9 = 18
Smallest 1-digit number is 0 and 0 + 0 = 0
Input: N = 2
Output:
Largest = 198
Smallest = 20
方法:
- 对于最大的:答案将是2 *(10 N – 1),因为两个n位数字之和的序列将继续进行,例如2 * 9、2 * 99、2 * 999,…
- 对于最小的:
- 如果N = 1,则答案将为0 。
- 如果N> 1,则答案将是2 *(10 N – 1 ),因为两个n位数字之和的序列将继续为0、20、200、2000等。
下面是上述方法的实现:
C++
// C++ implementation of the approach
#include
using namespace std;
// Function to return the smallest sum
// of 2 n-digit numbers
int smallestSum(int n)
{
if (n == 1)
return 0;
return (2 * pow(10, n - 1));
}
// Function to return the largest sum
// of 2 n-digit numbers
int largestSum(int n)
{
return (2 * (pow(10, n) - 1));
}
// Driver code
int main()
{
int n = 4;
cout << "Largest = " << largestSum(n) << endl;
cout << "Smallest = " << smallestSum(n);
return 0;
}
Java
// Java implementation of the approach
class GFG {
// Function to return the smallest sum
// of 2 n-digit numbers
static int smallestSum(int n)
{
if (n == 1)
return 0;
return (2 * (int)Math.pow(10, n - 1));
}
// Function to return the largest sum
// of 2 n-digit numbers
static int largestSum(int n)
{
return (2 * ((int)Math.pow(10, n) - 1));
}
// Driver code
public static void main(String args[])
{
int n = 4;
System.out.println("Largest = " + largestSum(n));
System.out.print("Smallest = " + smallestSum(n));
}
}
Python3
# Python3 implementation of the approach
# Function to return the smallest sum
# of 2 n-digit numbers
def smallestSum(n):
if (n == 1):
return 0
return (2 * pow(10, n - 1))
# Function to return the largest sum
# of 2 n-digit numbers
def largestSum(n):
return (2 * (pow(10, n) - 1))
# Driver code
n = 4
print("Largest = ", largestSum(n))
print("Smallest = ", smallestSum(n))
C#
// C# implementation of the approach
using System;
class GFG {
// Function to return the smallest sum
// of 2 n-digit numbers
static int smallestSum(int n)
{
if (n == 1)
return 0;
return (2 * (int)Math.Pow(10, n - 1));
}
// Function to return the largest sum
// of 2 n-digit numbers
static int largestSum(int n)
{
return (2 * ((int)Math.Pow(10, n) - 1));
}
// Driver code
public static void Main()
{
int n = 4;
Console.WriteLine("Largest = " + largestSum(n));
Console.Write("Smallest = " + smallestSum(n));
}
}
PHP
Javascript
输出:
Largest = 19998
Smallest = 2000