File tree 5 files changed +63
-3
lines changed
solution/0600-0699/0693.Binary Number with Alternating Bits
5 files changed +63
-3
lines changed Original file line number Diff line number Diff line change 54
54
<li><code>1 <= n <= 2<sup>31</sup> - 1</code></li>
55
55
</ul >
56
56
57
-
58
57
## 解法
59
58
60
59
<!-- 这里可写通用的实现逻辑 -->
61
60
61
+ 假设 01 交替出现,那么我们可以通过错位异或将尾部全部转为 1,加 1 可以得到 2 的幂次的一个数 n(n 中只有一个位是 1),接着利用 ` n & (n - 1) ` 可以消除最后一位的 1。
62
+
63
+ 此时判断是否为 0,若是,说明假设成立,是 01 交替串。
64
+
62
65
<!-- tabs:start -->
63
66
64
67
### ** Python3**
65
68
66
69
<!-- 这里可写当前语言的特殊实现逻辑 -->
67
70
68
71
``` python
69
-
72
+ class Solution :
73
+ def hasAlternatingBits (self , n : int ) -> bool :
74
+ n = (n ^ (n >> 1 )) + 1
75
+ return (n & (n - 1 )) == 0
70
76
```
71
77
72
78
### ** Java**
73
79
74
80
<!-- 这里可写当前语言的特殊实现逻辑 -->
75
81
76
82
``` 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++**
77
92
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
+ };
78
101
```
79
102
80
103
### **...**
Original file line number Diff line number Diff line change 58
58
### ** Python3**
59
59
60
60
``` python
61
-
61
+ class Solution :
62
+ def hasAlternatingBits (self , n : int ) -> bool :
63
+ n = (n ^ (n >> 1 )) + 1
64
+ return (n & (n - 1 )) == 0
62
65
```
63
66
64
67
### ** Java**
65
68
66
69
``` 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++**
67
79
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
+ };
68
88
```
69
89
70
90
### **...**
Original file line number Diff line number Diff line change
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 number Diff line number Diff line change
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 number Diff line number Diff line change
1
+ class Solution :
2
+ def hasAlternatingBits (self , n : int ) -> bool :
3
+ n = (n ^ (n >> 1 )) + 1
4
+ return (n & (n - 1 )) == 0
You can’t perform that action at this time.
0 commit comments