2013-11-04 106 views
0

是否有任何有效的方法來查找給定數字n的二進制表示的二進制表示? 凡1 < = N < = 600000二進制表示的二進制表示

實施例:用於取n = 2 所以,2二進制表示爲然後10 ,答案是10的二進制表示,即1010

+1

你的意思「的二進制表示(數字的二進制表示ñ重新解釋爲一個基10號)」 –

+0

是的,這正是我需要的。 –

回答

0

這是離開我的頭頂,對於大多數目的來說應該足夠快。適用於包括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); 
     } 
    } 
} 
+0

它不會導致C/C++中的溢出?因爲pow(10,i)使用的值大於界限。 –

+0

是的,這就是我面臨的問題。直到524,287,但沒有進一步.. –

+0

@AnkurMishra這是C#(不是語言被指定),並沒有出現溢出(因此檢查算術)。隨意自己驗證功能 - 我不會提供任何保證。我只是將它改進爲100萬。 – NPSF3000