Find the K-Beauty of a Number
Problem
The k-beauty of an integer num is the number of length-k substrings of num (read as a string) that are divisors of num. Leading zeros are allowed, but 0 is never a divisor. Return the k-beauty of num.
num = 240, k = 22def divisorSubstrings(num, k):
s = str(num) # read num as its digit string
count = 0
# slide a length-k window across the digits
for i in range(len(s) - k + 1):
window = int(s[i:i + k]) # the substring as an integer
if window != 0 and num % window == 0:
count += 1 # it divides num
return count
function divisorSubstrings(num, k) {
const s = String(num); // read num as its digit string
let count = 0;
// slide a length-k window across the digits
for (let i = 0; i + k <= s.length; i++) {
const window = Number(s.slice(i, i + k)); // substring as integer
if (window !== 0 && num % window === 0) {
count++; // it divides num
}
}
return count;
}
int divisorSubstrings(int num, int k) {
String s = Integer.toString(num); // read num as its digit string
int count = 0;
// slide a length-k window across the digits
for (int i = 0; i + k <= s.length(); i++) {
int window = Integer.parseInt(s.substring(i, i + k));
if (window != 0 && num % window == 0) {
count++; // it divides num
}
}
return count;
}
int divisorSubstrings(int num, int k) {
string s = to_string(num); // read num as its digit string
int count = 0;
// slide a length-k window across the digits
for (int i = 0; i + k <= (int)s.size(); i++) {
int window = stoi(s.substr(i, k)); // substring as integer
if (window != 0 && num % window == 0) {
count++; // it divides num
}
}
return count;
}
Explanation
The k-beauty asks a small counting question: among all contiguous k-digit chunks of num, how many evenly divide num? Because the chunks must be contiguous and of fixed length, this is a textbook fixed-size sliding window over the digit string.
First convert num to its string form s. A window starting at index i covers s[i .. i+k-1]. The first valid start is 0 and the last is len(s) - k, so the loop runs len(s) - k + 1 times — one window for every position the frame can sit.
For each window we read those k characters as an integer. Leading zeros are allowed, so "04" becomes 4 and "00" becomes 0. Parsing back to an integer handles this automatically.
We then test two conditions before counting it: the value must be non-zero (zero divides nothing), and num % window == 0 (it actually divides num). Only when both hold do we increment count.
Example: for num = 430043, k = 2 the windows are 43, 30, 00, 04, 43. Only the two 43s divide 430043 (and 00 is skipped because the value is 0), so the answer is 2.