Find the K-Beauty of a Number

easy sliding window string math

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.

Inputnum = 240, k = 2
Output2
Length-2 windows of "240": "24" (240 % 24 = 0 ✓) and "40" (240 % 40 = 0 ✓). Both divide 240, so the k-beauty is 2.

def 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;
}
Time: O(n · k) Space: O(n)