Skip to content

Commit 16ec521

Browse files
committed
feat: add solutions to lc problem: No.0693. Binary Number with Alternating Bits
1 parent d2226b3 commit 16ec521

File tree

5 files changed

+63
-3
lines changed

5 files changed

+63
-3
lines changed

solution/0600-0699/0693.Binary Number with Alternating Bits/README.md

+25-2
Original file line numberDiff line numberDiff line change
@@ -54,27 +54,50 @@
5454
<li><code>1 <= n <= 2<sup>31</sup> - 1</code></li>
5555
</ul>
5656

57-
5857
## 解法
5958

6059
<!-- 这里可写通用的实现逻辑 -->
6160

61+
假设 01 交替出现,那么我们可以通过错位异或将尾部全部转为 1,加 1 可以得到 2 的幂次的一个数 n(n 中只有一个位是 1),接着利用 `n & (n - 1)` 可以消除最后一位的 1。
62+
63+
此时判断是否为 0,若是,说明假设成立,是 01 交替串。
64+
6265
<!-- tabs:start -->
6366

6467
### **Python3**
6568

6669
<!-- 这里可写当前语言的特殊实现逻辑 -->
6770

6871
```python
69-
72+
class Solution:
73+
def hasAlternatingBits(self, n: int) -> bool:
74+
n = (n ^ (n >> 1)) + 1
75+
return (n & (n - 1)) == 0
7076
```
7177

7278
### **Java**
7379

7480
<!-- 这里可写当前语言的特殊实现逻辑 -->
7581

7682
```java
83+
class Solution {
84+
public boolean hasAlternatingBits(int n) {
85+
n = (n ^ (n >> 1)) + 1;
86+
return (n & (n - 1)) == 0;
87+
}
88+
}
89+
```
90+
91+
### **C++**
7792

93+
```cpp
94+
class Solution {
95+
public:
96+
bool hasAlternatingBits(int n) {
97+
n ^= (n >> 1);
98+
return (n & ((long) n + 1)) == 0;
99+
}
100+
};
78101
```
79102
80103
### **...**

solution/0600-0699/0693.Binary Number with Alternating Bits/README_EN.md

+21-1
Original file line numberDiff line numberDiff line change
@@ -58,13 +58,33 @@
5858
### **Python3**
5959

6060
```python
61-
61+
class Solution:
62+
def hasAlternatingBits(self, n: int) -> bool:
63+
n = (n ^ (n >> 1)) + 1
64+
return (n & (n - 1)) == 0
6265
```
6366

6467
### **Java**
6568

6669
```java
70+
class Solution {
71+
public boolean hasAlternatingBits(int n) {
72+
n = (n ^ (n >> 1)) + 1;
73+
return (n & (n - 1)) == 0;
74+
}
75+
}
76+
```
77+
78+
### **C++**
6779

80+
```cpp
81+
class Solution {
82+
public:
83+
bool hasAlternatingBits(int n) {
84+
n ^= (n >> 1);
85+
return (n & ((long) n + 1)) == 0;
86+
}
87+
};
6888
```
6989
7090
### **...**
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
class Solution {
2+
public:
3+
bool hasAlternatingBits(int n) {
4+
n ^= (n >> 1);
5+
return (n & ((long) n + 1)) == 0;
6+
}
7+
};
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
class Solution {
2+
public boolean hasAlternatingBits(int n) {
3+
n = (n ^ (n >> 1)) + 1;
4+
return (n & (n - 1)) == 0;
5+
}
6+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
class Solution:
2+
def hasAlternatingBits(self, n: int) -> bool:
3+
n = (n ^ (n >> 1)) + 1
4+
return (n & (n - 1)) == 0

0 commit comments

Comments
 (0)