-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathPowerOfK.java
50 lines (47 loc) · 1.11 KB
/
PowerOfK.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
package by.andd3dfx.numeric;
/**
* <pre>
* Given an integer n, return true if it is a power of k. Otherwise, return false.
*
* An integer n is a power of k, if there exists an integer x such that n == k^x.
*
* Example 1:
*
* Input: n = 64, k = 4
* Output: true
* Explanation: 64 = 4^3
*
* Example 2:
*
* Input: n = 0, k = 3
* Output: false
* Explanation: There is no x where 3^x = 0.
*
* Example 3:
*
* Input: n = -1, k = 2
* Output: false
* Explanation: There is no x where 2^x = (-1).
* </pre>
*
* @see <a href="https://youtu.be/E1Gue5EcvK4">Video solution</a>
*/
public class PowerOfK {
public static boolean isPowerOfK(int n, int k) {
while (n > 0 && n % k == 0) {
n /= k;
}
return n == 1;
}
/**
* n = k^x => log_k (n) = x
* log_a (b) = ln(b) /ln(a) = lg(b)/lg(a)
*/
public static boolean isPowerOfK_usingLog(int n, int k) {
if (n <= 0) {
return false;
}
var power = Math.round(Math.log(n) / Math.log(k));
return Math.pow(k, power) == n;
}
}