📌  相关文章
📜  最小化 A 和 B 的数字之和,使得 A + B = N

📅  最后修改于: 2021-10-25 06:47:35             🧑  作者: Mango

给定一个整数N ,任务是找到两个正整数AB ,使得A + B = N并且AB的数字之和最小。打印AB的数字总和。
例子:

方法:如果N10的幂,那么答案将是10否则答案将是N的数字之和。很明显,答案不能小于N的数字之和,因为每当产生进位时数字之和就会减少。而且,当N10的幂时,显然答案不可能是1 ,所以答案是10 。因为AB不能为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


Javascript


输出:
21

如果您希望与专家一起参加现场课程,请参阅DSA 现场工作专业课程学生竞争性编程现场课程