Skip to content

Commit cb5eb08

Browse files
committed
is power of four
1 parent 77cc6fc commit cb5eb08

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed

BinaryManipulation/PowOfFourSln.cs

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
using System;
2+
using System.Collections.Generic;
3+
using System.Linq;
4+
using System.Text;
5+
using System.Threading.Tasks;
6+
7+
namespace BinarySearch.Lib
8+
{
9+
// Given an integer (signed 32 bits), write a function to check whether it is a power of 4.
10+
11+
// Example:
12+
// Given num = 16, return true. Given num = 5, return false.
13+
14+
// Follow up: Could you solve it without loops/recursion?
15+
public class Solution
16+
{
17+
public bool IsPowerOfFour(int num)
18+
{
19+
//4d: 0010Binary 3d: 1100 0010 & 1100 = 0
20+
//16d:00001 15d: 11110 00001 & 11110 = 0
21+
return (num&(num-1)) == 0 && (num & 0x55555555) != 0;
22+
//0x55555555 is to remove those power of 2 but not power of 4
23+
//so that the value 1 always appears at the odd index
24+
}
25+
}
26+
}

0 commit comments

Comments
 (0)