LeetCode - Algorithms - 476. Number Complement

Problem

476. Number Complement This question is the same as 1009

Java

naive

1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution {
public int findComplement(int num) {
int r = 0;
String s = Integer.toBinaryString(num);
final int N = s.length();
char[] a = new char[N];
for (int i = 0; i < N; i++) {
a[i] = s.charAt(i) == '0' ? '1' : '0';
}
r = Integer.parseInt(String.valueOf(a),2);
return r;
}
}

Submission Detail

  • 149 / 149 test cases passed.
  • Runtime: 1 ms, faster than 35.06% of Java online submissions for Number Complement.
  • Memory Usage: 38.5 MB, less than 5.05% of Java online submissions for Number Complement.

2

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution {
public int findComplement(int num) {
String s = Integer.toBinaryString(num);
int r = 0;
final int N = s.length();
char[] a = s.toCharArray();
if (a[N - 1] == '0')
r = 1;
for (int i = N - 2; i >= 0; i--) {
if (a[i] == '0')
r += 2 << (N - 2 - i);
}
return r;
}
}

Submission Detail

  • 149 / 149 test cases passed.
  • Runtime: 1 ms, faster than 35.06% of Java online submissions for Number Complement.
  • Memory Usage: 37.7 MB, less than 18.78% of Java online submissions for Number Complement.

3

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution {
public int findComplement(int num) {
String s = Integer.toBinaryString(num);
int r = 0;
final int N = s.length();
if (s.charAt(N - 1) == '0')
r = 1;
for (int i = N - 2; i >= 0; i--) {
if (s.charAt(i) == '0')
r += 2 << (N - 2 - i);
}
return r;
}
}

Submission Detail

  • 149 / 149 test cases passed.
  • Runtime: 0 ms, faster than 100.00% of Java online submissions for Number Complement.
  • Memory Usage: 36.4 MB, less than 49.07% of Java online submissions for Number Complement.

4

1009. Complement of Base 10 Integer

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution {
public int bitwiseComplement(int N) {
String s = Integer.toBinaryString(N);
int r = 0;
final int LEN = s.length();
if (s.charAt(LEN - 1) == '0')
r = 1;
for (int i = LEN - 2; i >= 0; i--) {
if (s.charAt(i) == '0')
r += 2 << (LEN - 2 - i);
}
return r;
}
}

Submission Detail

  • 128 / 128 test cases passed.
  • Runtime: 0 ms, faster than 100.00% of Java online submissions for Complement of Base 10 Integer.
  • Memory Usage: 36.5 MB, less than 29.82% of Java online submissions for Complement of Base 10 Integer.