-
Notifications
You must be signed in to change notification settings - Fork 0
/
Power_of_two.cs
35 lines (24 loc) · 1.03 KB
/
Power_of_two.cs
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
namespace CodingChallenges;
[TestClass]
public class Power_of_two {
/*
Power of two
Complete the function power_of_two/powerOfTwo (or equivalent, depending on your language) that determines if a given non-negative integer is a power of two. From the corresponding Wikipedia entry:
a power of two is a number of the form 2n where n is an integer, i.e. the result of exponentiation with number two as the base and integer n as the exponent.
You may assume the input is always valid.
Examples
power_of_two?(1024) # true
power_of_two?(4096) # true
power_of_two?(333) # false
Beware of certain edge cases - for example, 1 is a power of 2 since 2^0 = 1 and 0 is not a power of 2.
*/
[TestMethod]
public void Test() {
Assert.IsTrue(PowerOfTwo(1024));
Assert.IsTrue(PowerOfTwo(4096));
Assert.IsTrue(PowerOfTwo(2));
Assert.IsFalse(PowerOfTwo(333));
Assert.IsFalse(PowerOfTwo(5));
}
public static bool PowerOfTwo(int n) => n > 0 && (n & (n - 1)) == 0;
}