Skip to content
This repository was archived by the owner on Dec 19, 2023. It is now read-only.

Commit be31dba

Browse files
committed
Add problem 1009
1 parent 8e0df53 commit be31dba

File tree

2 files changed

+50
-0
lines changed

2 files changed

+50
-0
lines changed

algorithms/1009/README.md

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
## 1009. Complement of Base 10 Integer
2+
3+
Every non-negative integer `N` has a binary representation. For example, `5` can be represented as `"101"` in binary, 11 as "1011" in binary, and so on. Note that except for `N = 0`, there are no leading zeroes in any binary representation.
4+
5+
The *complement* of a binary representation is the number in binary you get when changing every `1` to a `0` and `0` to a `1`. For example, the complement of `"101"` in binary is `"010"` in binary.
6+
7+
For a given number `N` in base-10, return the complement of it's binary representation as a base-10 integer.
8+
9+
<br>
10+
11+
**Example 1:**
12+
<pre>
13+
<b>Input:</b> 5
14+
<b>Output:</b> 2
15+
<b>Explanation:</b> 5 is "101" in binary, with complement "010" in binary, which is 2 in
16+
base-10.
17+
</pre>
18+
19+
**Example 2:**
20+
<pre>
21+
<b>Input:</b> 7
22+
<b>Output:</b> 0
23+
<b>Explanation:<b> 7 is "111" in binary, with complement "000" in binary, which is 0 in base-10.
24+
</pre>
25+
26+
**Example 3:**
27+
<pre>
28+
<b>Input:</b> 10
29+
<b>Output:</b> 5
30+
<b>Explanation:</b> 10 is "1010" in binary, with complement "0101" in binary, which is 5 in base-10.
31+
</pre>
32+
33+
**Note:**
34+
1. `0 <= N < 10^9`
35+
2. This question is the same as 476: https://leetcode.com/problems/number-complement/`

algorithms/1009/solution.go

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
package main
2+
3+
// Time and space complexity, O(1)
4+
func bitwiseComplement(N int) int {
5+
if N == 0 {
6+
return 1
7+
}
8+
var c int
9+
for m := 1; N != 0; m, N = m*2, N>>1 {
10+
if N&1 != 1 {
11+
c += m
12+
}
13+
}
14+
return c
15+
}

0 commit comments

Comments
 (0)