carloscn / structstudy

Leetcode daily trainning by using C/C++/RUST programming.
4 stars 1 forks source link

leetcode2269: Find the K-Beauty of a Number #371

Open carloscn opened 1 year ago

carloscn commented 1 year ago

Description

The k-beauty of an integer num is defined as the number of substrings of num when it is read as a string that meet the following conditions:

It has a length of k. It is a divisor of num. Given integers num and k, return the k-beauty of num.

Note:

Leading zeros are allowed. 0 is not a divisor of any value. A substring is a contiguous sequence of characters in a string.

Example 1:

Input: num = 240, k = 2 Output: 2 Explanation: The following are the substrings of num of length k:

Example 2:

Input: num = 430043, k = 2 Output: 2 Explanation: The following are the substrings of num of length k:

Constraints:

1 <= num <= 109 1 <= k <= num.length (taking num as a string)

carloscn commented 1 year ago

Analysis

static int32_t divisor_substrings(int32_t num, int32_t k)
{
    int32_t ret = 0;
    size_t len = 0;
    char num_str[16 + 1] = {'\0'};

    sprintf(num_str, "%d", num);
    len = strlen(num_str);

    if (len < k) {
        goto finish;
    } else if (len == k) {
        ret = 1;
        goto finish;
    }

    for (size_t i = 0; i < len - k + 1; i ++) {
        char buffer[17] = {'\0'};
        int32_t val = 0;
        for (size_t j = 0; j < k; j ++) {
            buffer[j] = num_str[j + i];
        }
        val = atoi(buffer);
        if (val != 0) {
            ret += (num % val) == 0;
        }
    }

finish:
    return ret;
}
carloscn commented 1 year ago

Code

https://review.gerrithub.io/c/carloscn/structstudy/+/1170435 https://github.com/carloscn/structstudy/commit/950a959e323455718d49d96909eb0c7a1f33688d