Skip to content

Commit 712e6df

Browse files
committed
Added 1 solution & modified 1 solution
1 parent 353e58d commit 712e6df

File tree

2 files changed

+50
-2
lines changed

2 files changed

+50
-2
lines changed

Easy/Power of four.java

Lines changed: 17 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,20 @@
11
class Solution {
2-
public boolean isPowerOfFour(int num) {
3-
return num>0 && (num&(num - 1))== 0 && (num-1)%3 == 0;
2+
public boolean isPowerOfFour(int num) {
3+
long start = 0;
4+
long end = num / 4;
5+
while (start <= end) {
6+
long mid = (start + end) / 2;
7+
long pow = (long) Math.pow(4, mid);
8+
if (pow == (long) num) {
9+
return true;
10+
}
11+
else if (pow > (long) num) {
12+
end = mid - 1;
13+
}
14+
else {
15+
start = mid + 1;
16+
}
417
}
18+
return false;
19+
}
520
}
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
class Solution {
2+
enum State {
3+
PROCESSING,
4+
PROCESSED
5+
}
6+
7+
public boolean leadsToDestination(int n, int[][] edges, int source, int destination) {
8+
Map<Integer, Set<Integer>> graph = new HashMap<>();
9+
for (int[] edge : edges) {
10+
graph.computeIfAbsent(edge[0], k -> new HashSet<>()).add(edge[1]);
11+
}
12+
return leadsToDestinationHelper(graph, source, destination, new State[n]);
13+
}
14+
15+
private boolean leadsToDestinationHelper(
16+
Map<Integer, Set<Integer>> graph, int source, int destination, State[] states
17+
) {
18+
if (states[source] != null) {
19+
return states[source] == State.PROCESSED;
20+
}
21+
if (!graph.containsKey(source)) {
22+
return source == destination;
23+
}
24+
states[source] = State.PROCESSING;
25+
for (Integer child : graph.getOrDefault(source, new HashSet<>())) {
26+
if (!leadsToDestinationHelper(graph, child, destination, states)) {
27+
return false;
28+
}
29+
}
30+
states[source] = State.PROCESSED;
31+
return true;
32+
}
33+
}

0 commit comments

Comments
 (0)