📜  将数字表示为以9结尾的正数之和

📅  最后修改于: 2021-04-29 04:35:37             🧑  作者: Mango

给定一个整数N ,任务是检查N是否可以表示为以9作为最后一位数字(9、19、29、39…)的整数之和。如果发现为真,则找到获得N所需的此类整数的最小计数。否则打印-1

例子:

天真的方法:这个问题可以看作是硬币找零问题的一种变体。对于这个问题,硬币可以用[9,19,29,39…。代替。直到最后一个小于N的数字(以9结尾)。

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

高效的方法:可以基于以下观察条件来优化上述方法:如果N最后一位是K ,则形成N至少需要(10-K)个最小数。

请按照以下步骤解决问题:

  1. 提取给定数字的最后一位, K = N%10
  2. 根据上述观察,总共需要(10 – K)个数字。现在,计算9 *(9-K) ,因为获得N所需的前9-K个数是9
  3. 现在,计算N – 9 *(9 – K)并存储在变量中,例如z 。如果z大于或等于9,并有9个为最后一个数字,打印10 – K的答案。否则,打印-1

下面是上述方法的实现:

C++
// C++ program for the above approach
  
#include 
using namespace std;
  
// Function to find the minimum count
// of numbers ending with 9 to form N
int minCountOfNumbers(int N)
{
    // Extract last digit of N
    int k = N % 10;
  
    // Calculate the last digit
    int z = N - (9 * (9 - k));
  
    // If the last digit
    // satisfies the condition
    if (z >= 9 && z % 10 == 9) {
        return 10 - k;
    }
    else
        return -1;
}
  
// Driver Code
int main()
{
    int N = 156;
    cout << minCountOfNumbers(N);
  
    return 0;
}


Java
// Java program for the above approach
import java.util.*;
  
class GFG{
  
// Function to find the minimum count
// of numbers ending with 9 to form N
static int minCountOfNumbers(int N)
{
      
    // Extract last digit of N
    int k = N % 10;
  
    // Calculate the last digit
    int z = N - (9 * (9 - k));
  
    // If the last digit
    // satisfies the condition
    if (z >= 9 && z % 10 == 9)
    {
        return 10 - k;
    }
    else
        return -1;
}
  
// Driver Code
public static void main(String[] args)
{
    int N = 156;
    System.out.print(minCountOfNumbers(N));
}
}
  
// This code is contributed by 29AjayKumar


Python3
# Python3 program for the above approach
  
# Function to find the minimum count
# of numbers ending with 9 to form N
def minCountOfNumbers(N):
      
    # Extract last digit of N
    k = N % 10
  
    # Calculate the last digit
    z = N - (9 * (9 - k))
  
    # If the last digit
    # satisfies the condition
    if (z >= 9 and z % 10 == 9):
        return 10 - k
    else:
        return -1
  
# Driver Code
if __name__ == '__main__':
      
    N = 156
      
    print(minCountOfNumbers(N))
  
# This code is contributed by mohit kumar 29


C#
// C# program for the above approach
using System;
  
class GFG{
  
// Function to find the minimum count
// of numbers ending with 9 to form N
static int minCountOfNumbers(int N)
{
      
    // Extract last digit of N
    int k = N % 10;
  
    // Calculate the last digit
    int z = N - (9 * (9 - k));
  
    // If the last digit
    // satisfies the condition
    if (z >= 9 && z % 10 == 9)
    {
        return 10 - k;
    }
    else
        return -1;
}
  
// Driver Code
public static void Main(String[] args)
{
    int N = 156;
      
    Console.Write(minCountOfNumbers(N));
}
}
  
// This code is contributed by 29AjayKumar


输出:
4

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