File tree Expand file tree Collapse file tree 2 files changed +52
-0
lines changed Expand file tree Collapse file tree 2 files changed +52
-0
lines changed Original file line number Diff line number Diff line change @@ -198,3 +198,4 @@ mod n0227_basic_calculator_ii;
198198mod n0228_summary_ranges;
199199mod n0229_majority_element_ii;
200200mod n0230_kth_smallest_element_in_a_bst;
201+ mod n0231_power_of_two;
Original file line number Diff line number Diff line change 1+ /**
2+ * [231] Power of Two
3+ *
4+ * Given an integer, write a function to determine if it is a power of two.
5+ *
6+ * Example 1:
7+ *
8+ *
9+ * Input: 1
10+ * Output: true
11+ * Explanation: 2^0 = 1
12+ *
13+ *
14+ * Example 2:
15+ *
16+ *
17+ * Input: 16
18+ * Output: true
19+ * Explanation: 2^4 = 16
20+ *
21+ * Example 3:
22+ *
23+ *
24+ * Input: 218
25+ * Output: false
26+ *
27+ */
28+ pub struct Solution { }
29+
30+ // submission codes start here
31+
32+ impl Solution {
33+ pub fn is_power_of_two ( n : i32 ) -> bool {
34+ let results: Vec < i32 > = ( 0 ..31 ) . map ( |x| 2_i32 . pow ( x) ) . collect ( ) ;
35+ results. binary_search ( & n) . is_ok ( )
36+ }
37+ }
38+
39+ // submission codes end
40+
41+ #[ cfg( test) ]
42+ mod tests {
43+ use super :: * ;
44+
45+ #[ test]
46+ fn test_231 ( ) {
47+ assert_eq ! ( Solution :: is_power_of_two( -1 ) , false ) ;
48+ assert_eq ! ( Solution :: is_power_of_two( 1 ) , true ) ;
49+ assert_eq ! ( Solution :: is_power_of_two( 1024 ) , true ) ;
50+ }
51+ }
You can’t perform that action at this time.
0 commit comments