File tree 5 files changed +101
-0
lines changed
solution/0400-0499/0476.Number Complement
5 files changed +101
-0
lines changed Original file line number Diff line number Diff line change @@ -122,6 +122,48 @@ function findComplement(num: number): number {
122
122
}
123
123
```
124
124
125
+ #### JavaScript
126
+
127
+ ``` js
128
+ /**
129
+ * @param {number} num
130
+ * @return {number}
131
+ */
132
+ var findComplement = function (num ) {
133
+ return num ^ (2 ** num .toString (2 ).length - 1 );
134
+ };
135
+ ```
136
+
137
+ <!-- tabs: end -->
138
+
139
+ <!-- solution: end -->
140
+
141
+ <!-- solution: start -->
142
+
143
+ ### 方法二:位运算(取反+按位与)
144
+
145
+ <!-- tabs: start -->
146
+
147
+ #### TypeScript
148
+
149
+ ``` ts
150
+ function findComplement(num : number ): number {
151
+ return ~ num & (2 ** num .toString (2 ).length - 1 );
152
+ }
153
+ ```
154
+
155
+ #### JavaScript
156
+
157
+ ``` js
158
+ /**
159
+ * @param {number} num
160
+ * @return {number}
161
+ */
162
+ function findComplement (num ) {
163
+ return ~ num & (2 ** num .toString (2 ).length - 1 );
164
+ }
165
+ ```
166
+
125
167
<!-- tabs: end -->
126
168
127
169
<!-- solution: end -->
Original file line number Diff line number Diff line change @@ -116,6 +116,48 @@ function findComplement(num: number): number {
116
116
}
117
117
```
118
118
119
+ #### JavaScript
120
+
121
+ ``` js
122
+ /**
123
+ * @param {number} num
124
+ * @return {number}
125
+ */
126
+ var findComplement = function (num ) {
127
+ return num ^ (2 ** num .toString (2 ).length - 1 );
128
+ };
129
+ ```
130
+
131
+ <!-- tabs: end -->
132
+
133
+ <!-- solution: end -->
134
+
135
+ <!-- solution: start -->
136
+
137
+ ### Solution 2: Bit Manipulation. Inversion + AND
138
+
139
+ <!-- tabs: start -->
140
+
141
+ #### TypeScript
142
+
143
+ ``` ts
144
+ function findComplement(num : number ): number {
145
+ return ~ num & (2 ** num .toString (2 ).length - 1 );
146
+ }
147
+ ```
148
+
149
+ #### JavaScript
150
+
151
+ ``` js
152
+ /**
153
+ * @param {number} num
154
+ * @return {number}
155
+ */
156
+ function findComplement (num ) {
157
+ return ~ num & (2 ** num .toString (2 ).length - 1 );
158
+ }
159
+ ```
160
+
119
161
<!-- tabs: end -->
120
162
121
163
<!-- solution: end -->
Original file line number Diff line number Diff line change
1
+ /**
2
+ * @param {number } num
3
+ * @return {number }
4
+ */
5
+ var findComplement = function ( num ) {
6
+ return num ^ ( 2 ** num . toString ( 2 ) . length - 1 ) ;
7
+ } ;
Original file line number Diff line number Diff line change
1
+ /**
2
+ * @param {number } num
3
+ * @return {number }
4
+ */
5
+ function findComplement ( num ) {
6
+ return ~ num & ( 2 ** num . toString ( 2 ) . length - 1 ) ;
7
+ }
Original file line number Diff line number Diff line change
1
+ function findComplement ( num : number ) : number {
2
+ return ~ num & ( 2 ** num . toString ( 2 ) . length - 1 ) ;
3
+ }
You can’t perform that action at this time.
0 commit comments