Skip to content

Commit 3604c24

Browse files
committed
solve problem Binary Number With Alternating Bits
1 parent 9d09bf8 commit 3604c24

File tree

5 files changed

+52
-1
lines changed

5 files changed

+52
-1
lines changed

README.md

+2-1
Original file line numberDiff line numberDiff line change
@@ -16,4 +16,5 @@ All solutions will be accepted!
1616
|557|[Reverse Words In A String III](https://leetcode-cn.com/problems/reverse-words-in-a-string-iii/description/)|[java/py/js](./algorithms/ReverseWordsInAStringIII)|Easy|
1717
|104|[Maximum Depth Of Binary Tree](https://leetcode-cn.com/problems/maximum-depth-of-binary-tree/description/)|[java/py/js](./algorithms/MaximumDepthOfBinaryTree)|Easy|
1818
|617|[Merge Two Binary Trees](https://leetcode-cn.com/problems/merge-two-binary-trees/description/)|[java/py/js](./algorithms/MergeTwoBinaryTrees)|Easy|
19-
|226|[Invert Binary Tree](https://leetcode-cn.com/problems/invert-binary-tree/description/)|[java/py/js]|(./algorithms/InvertBinaryTree)|Easy|
19+
|226|[Invert Binary Tree](https://leetcode-cn.com/problems/invert-binary-tree/description/)|[java/py/js]|(./algorithms/InvertBinaryTree)|Easy|
20+
|693|[Binary Number With Alternating Bits](https://leetcode-cn.com/problems/binary-number-with-alternating-bits/description/)|[java/py/js](./algorithms/BinaryNumberWithAlternatingBits)|Easy|
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
# Binary Number With Alternating Bits
2+
We can use bitwise to solve this problem
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
class Solution {
2+
public boolean hasAlternatingBits(int n) {
3+
int flag = -1;
4+
while (n > 0) {
5+
int res = n & 0x01;
6+
n >>= 1;
7+
if (flag == -1 || flag != res) {
8+
flag = res;
9+
} else {
10+
return false;
11+
}
12+
}
13+
return true;
14+
}
15+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
/**
2+
* @param {number} n
3+
* @return {boolean}
4+
*/
5+
var hasAlternatingBits = function(n) {
6+
let flag = null
7+
while (n > 0) {
8+
res = n & 0x01
9+
n >>= 1
10+
if (flag === null || flag !== res) {
11+
flag = res
12+
} else {
13+
return false
14+
}
15+
}
16+
return true
17+
};
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
class Solution(object):
2+
def hasAlternatingBits(self, n):
3+
"""
4+
:type n: int
5+
:rtype: bool
6+
"""
7+
flag = None
8+
while n > 0:
9+
res = n & 0x01
10+
n >>= 1
11+
if flag is None or flag != res:
12+
flag = res
13+
else:
14+
return False
15+
16+
return True

0 commit comments

Comments
 (0)