[C#][LeetCode][Easy] 476. Number Complement

心得:

題目要求將數字轉換為其補數,看起來滿單純的我就想不開硬幹了,由於不想借助C#內建的方法,所以自己實作二進位與十進位之間轉換。

題目:

Given a positive integer, output its complement number. The complement strategy is to flip the bits of its binary representation.

Note:

  1. The given integer is guaranteed to fit within the range of a 32-bit signed integer.
  2. You could assume no leading zero bit in the integer’s binary representation.
    答案:
  1. Normal - 硬幹
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
38
39
40
41
42
43
44
45
46
47
48

public class Solution {
public int FindComplement(int num) {
string str = ConvertMethod(num);
string ans = "";
for(int i = 0; i < str.Length; i++){
if(str[i] == '0'){
ans += "1";
}else{
ans += "0";
}
}

return ConvertMethod(ans);
}

private string ConvertMethod(int num){
string str = "";
while (num > 1)
{
str = num % 2 + str;
num = num / 2;
if (num == 1)
{
str = num + str;
num = 0;
}
}

return str;
}

private int ConvertMethod(string str)
{
int ans = 0;
for (int i = 0; i < str.Length; i++)
{
int tmp = 1;
for (int j = 1; j < (str.Length - i); j++)
{
tmp *= 2;
}
ans += tmp * int.Parse(str[i].ToString());
}

return ans;
}
}
  1. LinQ
1
2
3
4
5
6

public class Solution {
public int FindComplement(int num) {
return Convert.ToInt32(new string(Convert.ToString(num, 2).Select(x => x == '1' ? '0' : '1').ToArray()), 2);
}
}

參考:

  1. http://www.sggs.hc.edu.tw/sggsnew/comp/bccto2816.htm
  2. [C#] 轉2進位 / 10進位 / 16進位