Keep creating , Accelerate growth ! This is my participation 「 Nuggets day new plan · 6 Yuegengwen challenge 」 Of the 30 God , Click to see the event details
Given two integers num and k, consider a set of positive integers with the following properties:
The units digit of each integer is k. The sum of the integers is num. Return the minimum possible size of such a set, or -1 if no such set exists.
Note:
The set can contain multiple instances of the same integer, and the sum of an empty set is considered 0. The units digit of a number is the rightmost digit of the number.
Example 1:
Input: num = 58, k = 9
Output: 2
Explanation:
One valid set is [9,49], as the sum is 58 and each integer has a units digit of 9.
Another valid set is [19,39].
It can be shown that 2 is the minimum possible size of a valid set.
Example 2:
Input: num = 37, k = 2
Output: -1
Explanation: It is not possible to obtain a sum of 37 using only integers that have a units digit of 2.
Example 3:
Input: num = 0, k = 7
Output: 0
Explanation: The sum of an empty set is considered 0.
Note:
0 <= num <= 3000
0 <= k <= 9
According to the meaning , Given two integers num and k , Consider a set of positive integers with the following properties :
Returns the smallest possible size of such a collection , If no such collection exists , Then return to -1 . It should be noted that , A collection can contain multiple instances of the same integer , The sum of empty sets is considered to be 0 .
This problem can be counted as a mathematical problem , Let's assume that there is now a in the set n It's an integer , Then according to the above two conditions , We can know the following formula :
Because every bit of a positive number is k , Then it can become :
Get the above formula , You can get this num-n*k Must be 10 Multiple , So we traverse from 1 To 10 , If there is, the answer will be found , Otherwise go straight back to -1 .
Why do you know that if there is any result, it will be in 1 To 10 Between , Because we are right about 10 To take the mold .
The time complexity is O(1) , The space complexity is O(1) .
class Solution(object):
def minimumNumbers(self, num, k):
"""
:type num: int
:type k: int
:rtype: int
"""
if num == 0 :return 0
for i in range(1, 11):
if (num-i*k) % 10 == 0 and i*k <= num:
return i
return -1
298 / 298 test cases passed.
Status: Accepted
Runtime: 43 ms
Memory Usage: 13.3 MB
leetcode.com/contest/wee…
Your support is my greatest motivation