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

📅  最后修改于: 2021-05-08 17:53:11             🧑  作者: Mango

给定一个整数N ,任务是找到两个正整数AB ,使得A + B = NAB的数字总和最小。打印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


输出:
21