Member-only story
Leetcode 1492: The kth Factor of n
1 min readJun 28, 2020
In this Leetcode problem, we should return the kth factor of n
, or -1
if such factor doesn’t exist.
Solution
This is pretty much brute force:
- Test all integers from
1
ton
- Count the number of factors
current
, whencurrent = k
return the current factor value
Full code:
class Solution {
public int kthFactor(int n, int k) {
int current = 0;
for (int i = 1; i <= n; i++) {
if (n % i == 0) {
current++;
if (current == k) {
return i;
}
}
}
return -1;
}
}
Happy coding :)