Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 4ded1ce

Browse files
committed
docs: add solution 1012 [Java]
Complement of Base 10 Integer
1 parent ee59919 commit 4ded1ce

File tree

2 files changed

+73
-0
lines changed

2 files changed

+73
-0
lines changed
Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
## 十进制的反码
2+
3+
### 问题描述
4+
5+
每个非负整数 `N` 都有其二进制表示。例如, `5` 可以被表示为二进制 `"101"`,`11` 可以用二进制 `"1011"` 表示,依此类推。注意,除 `N = 0` 外,任何二进制表示中都不含前导零。
6+
7+
二进制的反码表示是将每个 `1` 改为 `0` 且每个 `0` 变为 `1`。例如,二进制数 `"101"` 的二进制反码为 `"010"`
8+
9+
给定十进制数 N,返回其二进制表示的反码所对应的十进制整数。
10+
11+
**示例1:**
12+
13+
```
14+
输入:5
15+
输出:2
16+
解释:5 的二进制表示为 "101",其二进制反码为 "010",也就是十进制中的 2 。
17+
```
18+
19+
**示例2:**
20+
21+
```
22+
输入:7
23+
输出:0
24+
解释:7 的二进制表示为 "111",其二进制反码为 "000",也就是十进制中的 0 。
25+
```
26+
27+
**示例3:**
28+
29+
```
30+
输入:10
31+
输出:5
32+
解释:10 的二进制表示为 "1010",其二进制反码为 "0101",也就是十进制中的 5 。
33+
```
34+
35+
**提示:**
36+
37+
1. `0 <= N < 10^9`
38+
39+
### 解法
40+
求余数,取反(`0 -> 1`, `1 -> 0`),累加结果。
41+
42+
注意 `N = 0` 的特殊情况。
43+
44+
```java
45+
class Solution {
46+
public int bitwiseComplement(int N) {
47+
if (N == 0) return 1;
48+
int res = 0;
49+
int exp = 0;
50+
while (N != 0) {
51+
int bit = N % 2 == 0 ? 1 : 0;
52+
res += Math.pow(2, exp) * bit;
53+
++exp;
54+
N >>= 1;
55+
}
56+
return res;
57+
}
58+
}
59+
```
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
class Solution {
2+
public int bitwiseComplement(int N) {
3+
if (N == 0) return 1;
4+
int res = 0;
5+
int exp = 0;
6+
while (N != 0) {
7+
int bit = N % 2 == 0 ? 1 : 0;
8+
res += Math.pow(2, exp) * bit;
9+
++exp;
10+
N >>= 1;
11+
}
12+
return res;
13+
}
14+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /