2269. Find the K-Beauty of a Number Easy
1/**
2 * [2269] Find the K-Beauty of a Number
3 *
4 * The k-beauty of an integer num is defined as the number of substrings
5 * of num when it is read as a string that meet the following conditions:
6 *
7 * It has a length of k.
8 * It is a divisor of num.
9 *
10 * Given integers num and k, return the k-beauty of num.
11 * Note:
12 *
13 * Leading zeros are allowed.
14 * 0 is not a divisor of any value.
15 *
16 * A substring is a contiguous sequence of characters in a string.
17 *
18 * Example 1:
19 *
20 * Input: num = 240, k = 2
21 * Output: 2
22 * Explanation: The following are the substrings of num of length k:
23 * - "24" from "<u>24</u>0": 24 is a divisor of 240.
24 * - "40" from "2<u>40</u>": 40 is a divisor of 240.
25 * Therefore, the k-beauty is 2.
26 *
27 * Example 2:
28 *
29 * Input: num = 430043, k = 2
30 * Output: 2
31 * Explanation: The following are the substrings of num of length k:
32 * - "43" from "<u>43</u>0043": 43 is a divisor of 430043.
33 * - "30" from "4<u>30</u>043": 30 is not a divisor of 430043.
34 * - "00" from "43<u>00</u>43": 0 is not a divisor of 430043.
35 * - "04" from "430<u>04</u>3": 4 is not a divisor of 430043.
36 * - "43" from "4300<u>43</u>": 43 is a divisor of 430043.
37 * Therefore, the k-beauty is 2.
38 *
39 *
40 * Constraints:
41 *
42 * 1 <= num <= 10^9
43 * 1 <= k <= num.length (taking num as a string)
44 *
45 */
46pub struct Solution {}
47
48// problem: https://leetcode.com/problems/find-the-k-beauty-of-a-number/
49// discuss: https://leetcode.com/problems/find-the-k-beauty-of-a-number/discuss/?currentPage=1&orderBy=most_votes&query=
50
51// submission codes start here
52
53impl Solution {
54 pub fn divisor_substrings(num: i32, k: i32) -> i32 {
55 let s = num.to_string();
56 let mut result = 0;
57 for i in 0..s.len() - k as usize + 1_usize {
58 let sub = s[i..i + k as usize].parse::<i32>().unwrap();
59 if sub != 0 && num % sub == 0 {
60 result += 1;
61 }
62 }
63 result
64 }
65}
66
67// submission codes end
68
69#[cfg(test)]
70mod tests {
71 use super::*;
72
73 #[test]
74 fn test_2269() {
75 assert_eq!(Solution::divisor_substrings(430043, 2), 2);
76 }
77}
78
Back
© 2025 bowen.ge All Rights Reserved.