Input: num =240, k =2 Output:2 Explanation: The following are the substrings of num of length k:-"24" from "**_24_** 0":24is a divisor of 240.-"40" from "2 _**40**_ ":40is a divisor of 240. Therefore, the k-beauty is2.
Input: num =430043, k =2 Output:2 Explanation: The following are the substrings of num of length k:-"43" from "_**43**_ 0043":43is a divisor of 430043.-"30" from "4 _**30**_ 043":30is not a divisor of 430043.-"00" from "43 _**00**_ 43":0is not a divisor of 430043.-"04" from "430 _**04**_ 3":4is not a divisor of 430043.-"43" from "4300 _**43**_ ":43is a divisor of 430043. Therefore, the k-beauty is2.
We want to count how many substrings of length k in the string representation of num are divisors of num. We can use a sliding window to extract each substring, convert it to an integer, and check if it divides num (ignoring zero substrings).
classSolution {
public:int divisorSubstrings(int num, int k) {
string s = to_string(num);
int ans =0;
for (int i =0; i <= s.size() - k; ++i) {
int val = stoi(s.substr(i, k));
if (val !=0&& num % val ==0) ++ans;
}
return ans;
}
};
classSolution {
publicintdivisorSubstrings(int num, int k) {
String s = Integer.toString(num);
int ans = 0;
for (int i = 0; i <= s.length() - k; ++i) {
int val = Integer.parseInt(s.substring(i, i + k));
if (val != 0 && num % val == 0) ++ans;
}
return ans;
}
}
1
2
3
4
5
6
7
8
9
10
11
classSolution {
fundivisorSubstrings(num: Int, k: Int): Int {
val s = num.toString()
var ans = 0for (i in0..s.length - k) {
val valNum = s.substring(i, i + k).toInt()
if (valNum !=0&& num % valNum ==0) ans++ }
return ans
}
}
1
2
3
4
5
6
7
8
9
classSolution:
defdivisorSubstrings(self, num: int, k: int) -> int:
s = str(num)
ans =0for i in range(len(s) - k +1):
val = int(s[i:i+k])
if val !=0and num % val ==0:
ans +=1return ans
1
2
3
4
5
6
7
8
9
10
11
12
13
14
impl Solution {
pubfndivisor_substrings(num: i32, k: i32) -> i32 {
let s = num.to_string();
letmut ans =0;
let k = k asusize;
for i in0..=s.len()-k {
let val = s[i..i+k].parse::<i32>().unwrap();
if val !=0&& num % val ==0 {
ans +=1;
}
}
ans
}
}