独立站shopify头条广告入口
【LetMeFly】2269.找到一个数字的 K 美丽值:字符串数字转换(模拟)
力扣题目链接:https://leetcode.cn/problems/find-the-k-beauty-of-a-number/
一个整数 num
的 k 美丽值定义为 num
中符合以下条件的 子字符串 数目:
- 子字符串长度为
k
。 - 子字符串能整除
num
。
给你整数 num
和 k
,请你返回 num
的 k 美丽值。
注意:
- 允许有 前缀 0 。
0
不能整除任何值。
一个 子字符串 是一个字符串里的连续一段字符序列。
示例 1:
输入:num = 240, k = 2 输出:2 解释:以下是 num 里长度为 k 的子字符串: - "240" 中的 "24" :24 能整除 240 。 - "240" 中的 "40" :40 能整除 240 。 所以,k 美丽值为 2 。
示例 2:
输入:num = 430043, k = 2 输出:2 解释:以下是 num 里长度为 k 的子字符串: - "430043" 中的 "43" :43 能整除 430043 。 - "430043" 中的 "30" :30 不能整除 430043 。 - "430043" 中的 "00" :0 不能整除 430043 。 - "430043" 中的 "04" :4 不能整除 430043 。 - "430043" 中的 "43" :43 能整除 430043 。 所以,k 美丽值为 2 。
提示:
1 <= num <= 109
1 <= k <= num.length
(将num
视为字符串)
解题方法:字符串数字转换
数据范围很小,直接按照题意将数字转为字符串和将字符串转为数字即可。
- 时间复杂度 O ( l e n ( n u m ) × k ) O(len(num)\times k) O(len(num)×k)
- 空间复杂度 O ( l e n ( n u m ) ) O(len(num)) O(len(num))
AC代码
C++
/** @Author: LetMeFly* @Date: 2025-03-10 12:36:42* @LastEditors: LetMeFly.xyz* @LastEditTime: 2025-03-10 12:41:03*/
class Solution {
public:int divisorSubstrings(int num, int k) {int ans = 0;string s = to_string(num);for (int i = 0; i + k <= s.size(); i++) {int thisNum = 0;for (int j = 0; j < k; j++) {thisNum = thisNum * 10 + s[i + j] - '0';}ans += thisNum && (num % thisNum == 0);}return ans;}
};
Python
'''
Author: LetMeFly
Date: 2025-03-10 12:43:11
LastEditors: LetMeFly.xyz
LastEditTime: 2025-03-10 12:44:22
'''
class Solution:def divisorSubstrings(self, num: int, k: int) -> int:s = str(num)ans = 0for i in range(len(s) - k + 1):thisNum = 0for j in range(k):thisNum = thisNum * 10 + ord(s[i + j]) - 48ans += thisNum and num % thisNum == 0return ans
Java
/** @Author: LetMeFly* @Date: 2025-03-10 12:48:24* @LastEditors: LetMeFly.xyz* @LastEditTime: 2025-03-10 12:49:58*/
class Solution {public int divisorSubstrings(int num, int k) {String s = String.valueOf(num);int ans = 0;for (int i = 0; i < s.length() - k + 1; i++) {int thisNum = Integer.parseInt(s.substring(i, i + k));if (thisNum > 0 && num % thisNum == 0) {ans++;}}return ans;}
}
Go
/** @Author: LetMeFly* @Date: 2025-03-10 12:46:00* @LastEditors: LetMeFly.xyz* @LastEditTime: 2025-03-10 12:47:20*/
package mainimport "strconv"func divisorSubstrings(num int, k int) (ans int) {s := strconv.Itoa(num)for i := 0; i < len(s) - k + 1; i++ {thisNum, _ := strconv.Atoi(s[i:i + k])if thisNum > 0 && num % thisNum == 0 {ans++}}return
}
同步发文于CSDN和我的个人博客,原创不易,转载经作者同意后请附上原文链接哦~
千篇源码题解已开源