LeetCode 2269: Find the K-Beauty of a Number
Problem Description
Explanation
To solve this problem, we can iterate through all possible substrings of length k
of the given number num
. For each substring, we check if it is a divisor of num
. If it is a divisor, we increment a counter. Finally, we return the counter as the k-beauty of the number.
Time Complexity
The time complexity of this approach is O(n * k), where n is the length of the number num
and k is the given length of the substrings.
Space Complexity
The space complexity is O(1) as we are not using any extra space that grows with the input size.
Solutions
class Solution {
public int beauty(int num, int k) {
String numStr = String.valueOf(num);
int count = 0;
for (int i = 0; i <= numStr.length() - k; i++) {
String sub = numStr.substring(i, i + k);
int subNum = Integer.parseInt(sub);
if (subNum != 0 && num % subNum == 0) {
count++;
}
}
return count;
}
}
Loading editor...