Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 9dbedce

Browse files
committed
Solve #231
1 parent e802410 commit 9dbedce

File tree

2 files changed

+52
-0
lines changed

2 files changed

+52
-0
lines changed

‎src/lib.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -198,3 +198,4 @@ mod n0227_basic_calculator_ii;
198198
mod n0228_summary_ranges;
199199
mod n0229_majority_element_ii;
200200
mod n0230_kth_smallest_element_in_a_bst;
201+
mod n0231_power_of_two;

‎src/n0231_power_of_two.rs

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
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+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /