【问题标题】:binary representation of binary re二进制 re 的二进制表示
【发布时间】:2013-11-04 18:40:57
【问题描述】:

是否有任何有效的方法来找到给定数字 n 的二进制表示的二进制表示? 其中 1

示例:让 n = 2 所以,2的二进制表示是10 那么答案就是10的二进制表示,即1010

【问题讨论】:

  • 您的意思是“(将数字 n 重新解释为以 10 为基数的二进制表示)的二进制表示”
  • 是的,这正是我需要的。

标签: binary


【解决方案1】:

这不是我的想法,对于大多数用途来说应该足够快。适用于高达(包括)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);
        }
    }
}

【讨论】:

  • 不会导致 C/C++ 溢出吗?因为 pow(10,i) 使用的 i 值大于界限。
  • @AnkurMishra 这是 C#(未指定语言)并且似乎没有溢出(因此检查了算术)。随意验证功能 - 我不会提供任何保证。我刚刚将其改进为 100 万。
  • 其实我应该在 C/C++ 中使用这个东西。那么,你能解释一下算法吗??
  • 它找出是否设置了一个位,然后将该位的十进制值添加到结果中。例如,如果设置了第二个位,它就知道要加 10。您应该能够算出其余部分,并在没有我帮助的情况下用 C/C++ 实现它。
猜你喜欢
  • 2021-12-21
  • 2021-10-06
  • 2011-04-17
  • 1970-01-01
  • 2011-03-24
  • 1970-01-01
  • 1970-01-01
  • 2016-05-01
  • 2015-03-27
相关资源
最近更新 更多