-
Notifications
You must be signed in to change notification settings - Fork 25
/
0693-binary-number-with-alternating-bits.js
64 lines (49 loc) · 1.37 KB
/
0693-binary-number-with-alternating-bits.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
55
56
57
58
59
60
61
62
63
64
// 693. Binary Number with Alternating Bits
// Easy 53% locked:false
// Given a positive integer, check whether it has alternating bits: namely, if
// two adjacent bits will always have different values.
// Example 1:
// Input: 5
// Output: True
// Explanation:
// The binary representation of 5 is: 101
// Example 2:
// Input: 7
// Output: False
// Explanation:
// The binary representation of 7 is: 111.
// Example 3:
// Input: 11
// Output: False
// Explanation:
// The binary representation of 11 is: 1011.
// Example 4:
// Input: 10
// Output: True
// Explanation:
// The binary representation of 10 is: 1010.
/**
* @param {number} n
* @return {boolean}
*/
const hasAlternatingBits = function(n) {
while (n) {
const prev = n & 1
n = n >> 1
if ((n & 1) === prev) return false
}
return true
}
console.log(hasAlternatingBits(4))
console.log(hasAlternatingBits(5))
console.log(hasAlternatingBits(7))
console.log(hasAlternatingBits(11))
console.log(hasAlternatingBits(10))
// Solution:
// 关键在于获得每一位上的比特,并与前或者后的比特比较
// & 1 运算可以获得末位的比特值。
// >> 算术右移(也可以是 >>> 逻辑右移,输入为正数),右移后,比较末位时候与之前的相同
// 题目,思路,代码都很简单。
// 时间复杂度 O(log(n))
// 空间复杂度 O(1)
// Submission Result: Accepted