FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[View Raw Code]
[Original HTTPS Page]
LeetCode/src/main/java/L0476_NumberComplement.java at master · LjyYano/LeetCode · GitHub
LjyYano
/
LeetCode
Public
Notifications
You must be signed in to change notification settings
Fork
125
Star
342
Code
Issues
0
Pull requests
0
Actions
Projects
Wiki
Security and quality
0
Insights
Additional navigation options
Code
Issues
Pull requests
Actions
Projects
Wiki
Security and quality
Insights
Expand file tree
Breadcrumbs
LeetCode
/
src
/
main
/
java
/
L0476_NumberComplement.java
Copy path
More file actions
More file actions
Latest commit
History
History
History
37 lines (34 loc) · 1001 Bytes
Breadcrumbs
LeetCode
/
src
/
main
/
java
/
L0476_NumberComplement.java
Copy path
File metadata and controls
37 lines (34 loc) · 1001 Bytes
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
public
class
L0476_NumberComplement
{
// 解法一:构造掩码
public
int
findComplement
(
int
num
) {
// 找到最高位
int
mask
=
num
;
mask
|=
mask
>>
1
;
mask
|=
mask
>>
2
;
mask
|=
mask
>>
4
;
mask
|=
mask
>>
8
;
mask
|=
mask
>>
16
;
// 异或得到补数
return
num
^
mask
;
}
// 解法二:使用 highestOneBit
public
int
findComplementV2
(
int
num
) {
// 找到最高位的位置
int
highestBit
=
Integer
.
highestOneBit
(
num
);
// 构造掩码:(highestBit << 1) - 1
int
mask
= (
highestBit
<<
1
) -
1
;
// 异或得到补数
return
num
^
mask
;
}
// 解法三:简洁写法
public
int
findComplementV3
(
int
num
) {
int
mask
=
1
;
int
temp
=
num
;
// 找到比 num 大的最小的 2^n - 1
while
(
temp
>
0
) {
temp
>>=
1
;
mask
<<=
1
;
}
return
(
mask
-
1
) ^
num
;
}
}
Back
|
FazBrowse Home
|
New Git URL