Skip to content

Commit cb80ec0

Browse files
author
Yi Gu
committed
[Math] add Solution to Power of Two and Power of Three
1 parent f53cd5b commit cb80ec0

File tree

2 files changed

+32
-0
lines changed

2 files changed

+32
-0
lines changed

Math/PowerThree.swift

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
/**
2+
* Question Link: https://leetcode.com/problems/power-of-three/
3+
* Primary idea: Use the largest 3^n int number to mod
4+
* Time Complexity: O(1), Space Complexity: O(1)
5+
*
6+
*/
7+
8+
class PowerThree {
9+
func isPowerOfThree(n: Int) -> Bool {
10+
guard n > 0 else {
11+
return false
12+
}
13+
14+
return 1162261467 % n == 0
15+
}
16+
}

Math/PowerTwo.swift

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
/**
2+
* Question Link: https://leetcode.com/problems/power-of-two/
3+
* Primary idea: Use and to solve the problem
4+
* Time Complexity: O(n), Space Complexity: O(1)
5+
*
6+
*/
7+
8+
class PowerTwo {
9+
func isPowerOfTwo(n: Int) -> Bool {
10+
guard n > 0 else {
11+
return false
12+
}
13+
14+
return n & (n - 1) == 0
15+
}
16+
}

0 commit comments

Comments
 (0)