-
Notifications
You must be signed in to change notification settings - Fork 1
/
power-of-two.js
54 lines (51 loc) · 1.07 KB
/
power-of-two.js
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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
/**
* Source: https://leetcode.com/problems/power-of-two/
* Tags: [Math,Bit Manipulation]
* Level: Easy
* Title: Power of Two
* Auther: @imcoddy
* Content: Given an integer, write a function to determine if it is a power of two.
*
*
* Credits:Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.
*
*
*
*
*
*
*
*
* Show Similar Problems
*
*
* (E) Number of 1 Bits
*/
/**
* @param {number} n
* @return {boolean}
*/
/**
* Memo:
* Complex: O(logn)
* Runtime: 204ms
* Tests: 1108 test cases passed
* Rank: B
* Updated: 2015-08-09
*/
var isPowerOfTwo = function(n) {
while (n > 1) {
if (n % 2 === 1) return false;
n = n >> 1;
}
return n === 1;
};
var should = require('should');
console.time('Runtime');
isPowerOfTwo(0).should.equal(false);
isPowerOfTwo(1).should.equal(true);
isPowerOfTwo(2).should.equal(true);
isPowerOfTwo(3).should.equal(false);
isPowerOfTwo(4).should.equal(true);
isPowerOfTwo(5).should.equal(false);
console.timeEnd('Runtime');