首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >二进制re的二进制表示

二进制re的二进制表示
EN

Stack Overflow用户
提问于 2013-11-04 09:06:28
回答 1查看 109关注 0票数 0

有什么有效的方法可以找到给定数n的二进制表示吗?其中1 <= n <= 600000

例子:让我们取n=2所以,2的二进制表示是10,答案是10的二进制表示,即1010。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-11-04 09:27:25

这是我的头顶,应该是足够快的大多数用途。为价值计,包括1,048,575。

代码语言:javascript
复制
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);
        }
    }
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/19764465

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档