leetcode405

时间:2023-03-08 16:57:05
public class Solution
{
string ConverToHex(string bit)
{
var s = "";
switch (bit)
{
case "":
s = "";
break;
case "":
s = "";
break;
case "":
s = "";
break;
case "":
s = "";
break;
case "":
s = "";
break;
case "":
s = "";
break;
case "":
s = "";
break;
case "":
s = "";
break;
case "":
s = "";
break;
case "":
s = "";
break;
case "":
s = "a";
break;
case "":
s = "b";
break;
case "":
s = "c";
break;
case "":
s = "d";
break;
case "":
s = "e";
break;
case "":
s = "f";
break;
}
return s;
} public string ToHex(int num)
{
var fuhao = ;
if (num < )
{
fuhao = -;
num = num * (-);
} //10进制转16进制,负数使用补码
var bitAry = new string[];
for (int i = ; i < bitAry.Length; i++)
{
bitAry[i] = "";
}
//STEP1:十进制转二进制
int index = ;
do
{
var x = num % ;
bitAry[index++] = x.ToString();
num = num / ;
} while (num != ); var list = bitAry.ToList(); //STEP2:正数使用原码,负数转补码
if (fuhao == -)
{
list.Clear(); bitAry[bitAry.Length - ] = "";//符号为设置为0 //计算反码
StringBuilder sbFan = new StringBuilder();
for (int i = ; i < bitAry.Length - ; i++)
{
if (bitAry[i] == "")
{
sbFan.Append("");
}
else
{
sbFan.Append("");
}
}
sbFan.Append("");//index=31的是符号位 //反码加1 var fanma = sbFan.ToString(); var step = ;
var first = true;
for (int i = ; i < fanma.Length - ; i++)
{
var x = Convert.ToInt32(fanma[i].ToString());
if (first)
{
first = false;
x = (x + ) % ;
list.Add(x.ToString());
if (x == )
{
step = ;
}
else
{
step = ;
}
}
else
{
list.Add(((x + step) % ).ToString());
if (x == && step == )
{
step = ;
}
else
{
step = ;
}
}
}
list.Add("");
} //STEP3:二进制转十六进制
string result = ""; if (fuhao == -)//负数
{
var temp = "";
for (int i = ; i < list.Count; i++)
{ if ((i + ) % != )//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 = ; i < list.Count; i++)
{
if ((i + ) % != )
{
temp = list[i] + temp;
}
else
{
temp = list[i] + temp;
var hex = ConverToHex(temp);
result = hex + result;
temp = "";
} } } var notZeroIndex = -;
for (int i = ; i < result.Length; i++)
{
if (result[i] != '')
{
notZeroIndex = i;
break;
}
}
if (notZeroIndex > )
{
result = result.Substring(notZeroIndex);
} if (result == "")
{
result = "";
} return result;
}
}

https://leetcode.com/problems/convert-a-number-to-hexadecimal/#/description