给定一个整数N ,任务是找到两个正整数A和B ,使得A + B = N且A和B的数字总和最小。打印A和B的数字总和。
例子:
Input: N = 16
Output: 7
(10 + 6) = 16 and (1 + 0 + 6) = 7
is minimum possible.
Input: N = 1000
Output: 10
(900 + 100) = 1000
方法:如果N是10的幂,那么答案将是10,否则答案将是N的数字总和。显然,答案不能小于N的位数之和,因为每当产生进位时位数的总和就会减少。此外,当N为10的幂时,答案显然不能为1 ,因此答案将为10 。由于A或B不能为0,因为它们两个都必须为正数。
下面是上述方法的实现:
C++
// C++ implementation of the approach
#include
using namespace std;
// Function to return the minimum
// possible sum of digits of A
// and B such that A + B = n
int minSum(int n)
{
// Find the sum of digits of n
int sum = 0;
while (n > 0) {
sum += (n % 10);
n /= 10;
}
// If num is a power of 10
if (sum == 1)
return 10;
return sum;
}
// Driver code
int main()
{
int n = 1884;
cout << minSum(n);
return 0;
}
Java
// Java implementation of the approach
class GFG
{
// Function to return the minimum
// possible sum of digits of A
// and B such that A + B = n
static int minSum(int n)
{
// Find the sum of digits of n
int sum = 0;
while (n > 0)
{
sum += (n % 10);
n /= 10;
}
// If num is a power of 10
if (sum == 1)
return 10;
return sum;
}
// Driver code
public static void main(String[] args)
{
int n = 1884;
System.out.print(minSum(n));
}
}
// This code is contributed by 29AjayKumar
Python3
# Python implementation of the approach
# Function to return the minimum
# possible sum of digits of A
# and B such that A + B = n
def minSum(n) :
# Find the sum of digits of n
sum = 0;
while (n > 0) :
sum += (n % 10);
n //= 10;
# If num is a power of 10
if (sum == 1) :
return 10;
return sum;
# Driver code
if __name__ == "__main__" :
n = 1884;
print(minSum(n));
# This code is contributed by AnkitRai01
C#
// C# implementation of the approach
using System;
class GFG
{
// Function to return the minimum
// possible sum of digits of A
// and B such that A + B = n
static int minSum(int n)
{
// Find the sum of digits of n
int sum = 0;
while (n > 0)
{
sum += (n % 10);
n /= 10;
}
// If num is a power of 10
if (sum == 1)
return 10;
return sum;
}
// Driver code
public static void Main(String[] args)
{
int n = 1884;
Console.Write(minSum(n));
}
}
// This code is contributed by PrinciRaj1992
输出:
21