给定一个整数N ,任务是检查N 是否可以表示为最后一位为9的整数之和(9, 19, 29, 39 …),或者不能。如果发现为真,则找到获得N所需的此类整数的最小计数。否则打印-1 。
例子:
Input: N = 156
Output: 4
Explanation:
156 = 9 + 9 + 9 + 129
Input: N = 60
Output: -1
Explanation:
No possible way to obtain sum 60 from numbers having 9 as the last digit.
朴素的方法:这个问题可以看作是硬币找零问题的一种变体。对于这个问题,硬币可以用 [9, 19, 29, 39 … 代替。直到最后一个小于 N 以 9 结尾的数字]。
时间复杂度: O(N 2 )
辅助空间: O(N)
有效的方法:上述方法可以根据观察进行优化,如果N的最后一位数字是 K ,那么正好需要(10 – K) 个最小数字来形成N 。
A sum N can be obtained by adding 10 – K numbers, where K is the last digit of N.
Therefore, sum N can be obtained by adding 9, (9 – K) times and adding N – (9 * (9 – K)) finally.
请按照以下步骤解决问题:
- 提取给定数字的最后一位, K = N % 10
- 使用上述观察,总共需要(10 – K) 个数字。现在,计算9 * (9 – K) ,因为获得N所需的前9 – K 个数字是9 。
- 现在,计算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
Javascript
4
时间复杂度: O(1)
辅助空间: O(1)