ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

[LeetCode] 2310. Sum of Numbers With Units Digit K

2022-06-19 14:05:54  阅读:341  来源: 互联网

标签:digit set int Sum 多重集 Digit 2310 num sum


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.

Constraints:

  • 0 <= num <= 3000
  • 0 <= k <= 9

个位数字为 K 的整数之和。

给你两个整数 num 和 k ,考虑具有以下属性的正整数多重集:

每个整数个位数字都是 k 。
所有整数之和是 num 。
返回该多重集的最小大小,如果不存在这样的多重集,返回 -1 。

注意:

多重集与集合类似,但多重集可以包含多个同一整数,空多重集的和为 0 。
个位数字 是数字最右边的数位。

来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/sum-of-numbers-with-units-digit-k
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

这是一道数学题。题目给了两个参数,num 和 k,问的是是否存在一些数字,他们的个位数都是 k,且他们的和等于 num。

这道题不难,但是紧张的时候思路容易乱。周赛的时候我就没想清楚,但是事后却可以写出来。

首先有几个 corner case。如果 k == 0,那么 num 的最后一位也必须是 0,否则就返回 -1。如果 num == 0,k == 0(参见例子三)。

接下来是一般的情形。对于任何一个 num 而言,能否找到若干个数字满足题意,其实只需要看这若干个数字的最后一位的加和是否等于 num 的最后一位。所以我们设一个变量 i ,让 i 遍历 1 到 9,来看看是否存在 i 个数字,他们的加和的最后一位等于 num 的最后一位,如果存在那一定就是有解的。

时间O(1) - 至多尝试九次

空间O(1)

Java实现

 1 class Solution {
 2     public int minimumNumbers(int num, int k) {
 3         // corner case
 4         if (num == 0) {
 5             return 0;
 6         }
 7         if (k == 0) {
 8             if (num % 10 == 0) {
 9                 return 1;
10             } else {
11                 return -1;
12             }
13         }
14 
15         // normal case
16         int lastDigit = num % 10;
17         for (int i = 1; i <= num / k; i++) {
18             if ((i * k) % 10 == lastDigit) {
19                 return i;
20             }
21         }
22         return -1;
23     }
24 }

 

LeetCode 题目总结

标签:digit,set,int,Sum,多重集,Digit,2310,num,sum
来源: https://www.cnblogs.com/cnoodle/p/16390383.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有