Leetcode - 2269. Find the K-Beauty of a Number

숲사람·2022년 6월 9일
0

멘타트 훈련

목록 보기
51/237

문제

숫자num이 주어지고 k길이가 주어질때, 숫자를 k만큼 쪼갠 수가 주어진 num의 몫이 될수 있는가? 있다면 몇개 존재하나?

Input: num = 430043, k = 2
Output: 2
Explanation: The following are the substrings of num of length k:
- "43" from "430043": 43 is a divisor of 430043.
- "30" from "430043": 30 is not a divisor of 430043.
- "00" from "430043": 0 is not a divisor of 430043.
- "04" from "430043": 4 is not a divisor of 430043.
- "43" from "430043": 43 is a divisor of 430043.
Therefore, the k-beauty is 2.

해결 O(k N)

int divisorSubstrings(int num, int k){
    int retcnt = 0;
    char snum[11];
    sprintf(snum, "%d", num);
    int nsize = strlen(snum);
    
    char *substr = (char *)calloc(k + 1, sizeof(char));
    int sub = 0;
    for (int i = 0; i <= nsize - k; i++) {
        strncpy(substr, snum + i, k);
        sscanf(substr, "%d", &sub);
        if (sub == 0)
            continue;
        if (num % sub == 0) // always check devide by zero
            retcnt++;
    }
    return retcnt;
}
profile
기록 & 정리 아카이브 용도 (보다 완성된 글은 http://soopsaram.com/documentudy)

0개의 댓글