You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: solution/0200-0299/0231.Power of Two/README_EN.md
+32-4Lines changed: 32 additions & 4 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -62,7 +62,11 @@ tags:
62
62
63
63
<!-- solution:start -->
64
64
65
-
### Solution 1
65
+
### Solution 1: Bit Manipulation
66
+
67
+
According to the properties of bit manipulation, executing $\texttt{n\&(n-1)}$ can eliminate the last bit 1ドル$ in the binary form of $n$. Therefore, if $n > 0$ and $\texttt{n\&(n-1)}$ results in 0ドル,ドル then $n$ is a power of 2ドル$.
68
+
69
+
The time complexity is $O(1),ドル and the space complexity is $O(1)$.
66
70
67
71
<!-- tabs:start -->
68
72
@@ -111,6 +115,16 @@ function isPowerOfTwo(n: number): boolean {
111
115
}
112
116
```
113
117
118
+
#### Rust
119
+
120
+
```rust
121
+
implSolution {
122
+
pubfnis_power_of_two(n:i32) ->bool {
123
+
n>0&& (n& (n-1)) ==0
124
+
}
125
+
}
126
+
```
127
+
114
128
#### JavaScript
115
129
116
130
```js
@@ -129,7 +143,11 @@ var isPowerOfTwo = function (n) {
129
143
130
144
<!-- solution:start -->
131
145
132
-
### Solution 2
146
+
### Solution 2: Lowbit
147
+
148
+
According to the definition of $\text{lowbit},ドル we know that $\text{lowbit}(x) = x \& (-x),ドル which can get the decimal number represented by the last bit 1ドル$ of $n$. Therefore, if $n > 0$ and $\text{lowbit}(n)$ equals $n,ドル then $n$ is a power of 2ドル$.
149
+
150
+
The time complexity is $O(1),ドル and the space complexity is $O(1)$.
0 commit comments