📌  相关文章
📜  获得给定总和所需的最小位数

📅  最后修改于: 2021-05-04 11:35:03             🧑  作者: Mango

给定整数N ,任务是查找生成数字总和等于N的数字所需的最小位数。

例子:

方法:可通过以下观察来解决该问题:

  1. 增量计数9 。因此,现在count等于最短数中的9。将N减少到N%9
  2. 现在,如果N超过0,则将count递增1
  3. 最后,打印计数作为答案。

下面是上述方法的实现:

C++
// C++ program to implement
// the above approach
#include 
using namespace std;
 
// Function to return the
// minimum count of digits
void mindigits(int n)
{
    // IF N is divisible by 9
    if (n % 9 == 0) {
 
        // Count of 9's is the answer
        cout << n / 9 << endl;
    }
    else {
 
        // If remainder is non-zero
        cout << (n / 9) + 1 << endl;
    }
}
 
// Driver Code
int main()
{
    int n1 = 24;
    int n2 = 14;
    mindigits(n1);
    mindigits(n2);
}


Java
// Java program to implement
// the above approach
// required to make the given sum
import java.util.*;
 
class Main {
 
    // Function to print the minimum
    // count of digits
    static void mindigits(int n)
    {
 
        // IF N is divisible by 9
        if (n % 9 == 0) {
 
            // Count of 9's is the answer
            System.out.println(n / 9);
        }
        else {
 
            // If remainder is non-zero
            System.out.println((n / 9) + 1);
        }
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        int n1 = 24;
        int n2 = 18;
        mindigits(n1);
        mindigits(n2);
    }
}


Python3
# Python3 program to implement
# the above approach
 
# Function to print the minimum
# count of digits
def mindigits(n):
     
    # IF N is divisible by 9
    if (n % 9 == 0):
 
        # Count of 9's is the answer
        print(n // 9);
    else:
 
        # If remainder is non-zero
        print((n // 9) + 1);
 
# Driver Code
if __name__ == '__main__':
     
    n1 = 24;
    n2 = 18;
     
    mindigits(n1);
    mindigits(n2);
 
# This code is contributed by amal kumar choubey


C#
// C# program to implement
// the above approach
using System;
 
class GFG{
 
// Function to print the minimum
// count of digits
static void mindigits(int n)
{
     
    // IF N is divisible by 9
    if (n % 9 == 0)
    {
         
        // Count of 9's is the answer
        Console.WriteLine(n / 9);
    }
    else
    {
         
        // If remainder is non-zero
        Console.WriteLine((n / 9) + 1);
    }
}
 
// Driver Code
public static void Main(String[] args)
{
    int n1 = 24;
    int n2 = 18;
     
    mindigits(n1);
    mindigits(n2);
}
}
 
// This code is contributed by 29AjayKumar


输出:
3
2

时间复杂度: O(1)
辅助空间: O(1)