public class Solution { string ConverToHex(string bit) { var s = ""; switch (bit) { case "0000": s = "0"; break; case "0001": s = "1"; break; case "0010": s = "2"; break; case "0011": s = "3"; break; case "0100": s = "4"; break; case "0101": s = "5"; break; case "0110": s = "6"; break; case "0111": s = "7"; break; case "1000": s = "8"; break; case "1001": s = "9"; break; case "1010": s = "a"; break; case "1011": s = "b"; break; case "1100": s = "c"; break; case "1101": s = "d"; break; case "1110": s = "e"; break; case "1111": s = "f"; break; } return s; } public string ToHex(int num) { var fuhao = 1; if (num < 0) { fuhao = -1; num = num * (-1); } //10进制转16进制,负数使用补码 var bitAry = new string[32]; for (int i = 0; i < bitAry.Length; i++) { bitAry[i] = "0"; } //STEP1:十进制转二进制 int index = 0; do { var x = num % 2; bitAry[index++] = x.ToString(); num = num / 2; } while (num != 0); var list = bitAry.ToList(); //STEP2:正数使用原码,负数转补码 if (fuhao == -1) { list.Clear(); bitAry[bitAry.Length - 1] = "1";//符号为设置为0 //计算反码 StringBuilder sbFan = new StringBuilder(); for (int i = 0; i < bitAry.Length - 1; i++) { if (bitAry[i] == "1") { sbFan.Append("0"); } else { sbFan.Append("1"); } } sbFan.Append("1");//index=31的是符号位 //反码加1 var fanma = sbFan.ToString(); var step = 0; var first = true; for (int i = 0; i < fanma.Length - 1; i++) { var x = Convert.ToInt32(fanma[i].ToString()); if (first) { first = false; x = (x + 1) % 2; list.Add(x.ToString()); if (x == 0) { step = 1; } else { step = 0; } } else { list.Add(((x + step) % 2).ToString()); if (x == 1 && step == 1) { step = 1; } else { step = 0; } } } list.Add("1"); } //STEP3:二进制转十六进制 string result = ""; if (fuhao == -1)//负数 { var temp = ""; for (int i = 0; i < list.Count; i++) { if ((i + 1) % 4 != 0)//0,1,2 { temp = list[i] + temp; } else { temp = list[i] + temp; var hex = ConverToHex(temp); result = hex + result; temp = ""; } } } else//正数 { var temp = ""; for (int i = 0; i < list.Count; i++) { if ((i + 1) % 4 != 0) { temp = list[i] + temp; } else { temp = list[i] + temp; var hex = ConverToHex(temp); result = hex + result; temp = ""; } } } var notZeroIndex = -1; for (int i = 0; i < result.Length; i++) { if (result[i] != '0') { notZeroIndex = i; break; } } if (notZeroIndex > 0) { result = result.Substring(notZeroIndex); } if (result == "00000000") { result = "0"; } return result; } }
https://leetcode.com/problems/convert-a-number-to-hexadecimal/#/description