有什么有效的方法可以找到给定数n的二进制表示吗?其中1 <= n <= 600000
例子:让我们取n=2所以,2的二进制表示是10,答案是10的二进制表示,即1010。
发布于 2013-11-04 09:27:25
这是我的头顶,应该是足够快的大多数用途。为价值计,包括1,048,575。
using System;
namespace ConsoleApplication5
{
class Program
{
static void Main(string[] args)
{
checked
{
uint i = 0;
while (true)
{
try
{
BinaryOfDecimalRepresentation(++i);
}
catch { Console.WriteLine("Works until " + i); break; }
}
while (true)
{
uint input = 0;
try
{
input = uint.Parse(Console.ReadLine());
}
catch { }
Console.WriteLine(
BinaryOfDecimalRepresentation(input) + " : " +
UInt64ToString(BinaryOfDecimalRepresentation(input)));
}
}
}
static ulong BinaryOfDecimalRepresentation(uint input)
{
checked
{
ulong result = 0;
for (int i = 0; i < 32; i++)
if ((input & 1 << i) != 0) result += (ulong)Math.Pow(10, i);
return result;
}
}
static char[] buffer = new char[64];
static string UInt64ToString(ulong input, bool trim = true)
{
for (int i = 0; i < 64; i++)
buffer[63 - i] = ((input & (ulong)1 << i) != 0) ? '1' : '0';
int firstOne = 0;
if (trim) while (buffer[firstOne] == '0') firstOne++;
return new string(buffer, firstOne, 64 - firstOne);
}
}
}https://stackoverflow.com/questions/19764465
复制相似问题