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

📅  最后修改于: 2021-10-26 05:47:28             🧑  作者: Mango

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

例子:

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

  1. 计数增加9 。因此,现在计数等于最短数字中的 9 的数量。减少NN % 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


Javascript


输出:
3
2

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