🔖

LeetCode #2269 Find the K-Beauty of a Number

2024/10/15に公開

問題概要

入力値:num(int), k(int)
出力値:int
Given integers num and k, return the k-beauty of num.
問題のリンク

入力例

Input: n = 240, k = 2
Output: 2

解答例1

計算量:O(n)
Sliding window
Python

class Solution(object):
    def divisorSubstrings(self, num, k):
        """
        :type num: int
        :type k: int
        :rtype: int
        """
        result = 0
        num_string = str(num)
        num_length = len(num_string)
        for i in range(num_length):
            right = i + k
            if right > num_length:
                break
            sub_string = num_string[i:right]
            sub_num = int(sub_string)
            if sub_num != 0 and num % sub_num == 0:
                result += 1
        return result

Runtime: 7ms
Beats: 99.07%

C++

class Solution {
public:
    int divisorSubstrings(int num, int k) {
        int result = 0;
        string num_string = to_string(num);
        int num_length = num_string.size();
        for (int i=0; i<num_length; i++) {
            if ((i+k) > num_length) {
                break;
            }
            int sub_num = stoi(num_string.substr(i, k));
            if (sub_num != 0 && num % sub_num == 0) {
                result += 1;
            }
        }
        return result;
    }
};

Runtime: 0ms
Beats: 100%

Discussion