C# 十进制转换为二进制
//第一次发文章哈😄
//字符串转反转函数
public static string Reverse(string s1)
{
string s2="";
for (int i = s1.Length-1; i >-1; i–)
{
s2+= s1[i];
}
return s2;
}
//十进制转换为二进制
public static string TenTransTwo(int n) { int i = 2;
string result = “”;
if (n % 2 == 0) { result += ‘0’; }
else { n = n - 1; result += ‘1’; }
while (n>=i) {
if ((n/i)%2==0) { result += ‘0’; }
else { n = n - i; result += ‘1’; } i = 2 * i; }
return Reverse(result); }
//测试
Console.WriteLine(“请输入一个正整数:”);
int n = Convert.ToInt32(Console.ReadLine());
Console.WriteLine(TenTransTwo(n));