心得:
題目要求將數字轉換為其補數,看起來滿單純的我就想不開硬幹了,由於不想借助C#內建的方法,所以自己實作二進位與十進位之間轉換。
題目:
Given a positive integer, output its complement number. The complement strategy is to flip the bits of its binary representation.
Note:
- The given integer is guaranteed to fit within the range of a 32-bit signed integer.
- You could assume no leading zero bit in the integer’s binary representation.
答案:
- Normal – 硬幹
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; } }
- LinQ
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); } }
參考: