不希望将二进制转换为十进制的输出?

时间:2015-12-07 17:09:57

标签: java string

  

给定二进制数作为输入将其转换为基数10(十进制系统)。注意,要将数字100111从二进制转换为十进制,值为1 * 2 ^ 5 + 0 * 2 ^ 4 + 0 * 2 ^ 3 + 1 * 2 ^ 2 + 1 * 2 ^ 1 + 1 * 2 ^ 0 。另请注意,这里的5是二进制数的长度。

MyApproach

要转换为十进制,我首先将代码从String转换为十进制。然后我解决了数字,直到它大于0并解决了表达式。

例如,对于数字10 = 0 * 2 ^ 0 + 1 * 2 ^ 1并解决了代码中的表达式。

  

我在最后一个测试用例中遇到错误的Ans。   任何人都可以指导我的代码有什么问题。?

以下是我的代码:

public int convert(String binary)
{
int p=0;
int decimal=0;

int number=Integer.parseInt(binary);
while(number>0)
{
  int temp = number%10;
     decimal += temp*Math.pow(2, p);
     number = number/10;
     p++;
  //write your code here

 }
 return decimal;
} 
}

Parameters     ActualOutput      ExpectedOutput

'10011010010'    null             1234

4 个答案:

答案 0 :(得分:1)

整数的最大值是(2 ^ 31-1),并且您从字符串解析为int的值大于该值。因此尝试使用Long代替int .. 下面的代码工作正常..请在下面查看..

public static int convert(String binary)
    {
    int p=0;
    int decimal=0;

    long number=Long.parseLong(binary);
    while(number>0)
    {
      long temp = number%10;
         decimal += temp*Math.pow(2, p);
         number = number/10;
         p++;
      //write your code here

     }
     return decimal;
    }  

答案 1 :(得分:1)

更简单,没有战俘:

int s=binary.length();

for (int pos=0;pos<s;pos++)
{
char c=binary.charAt(pos);
if (c=='1') decimal+=1;
if (pos<s-1) decimal*=2;
}

答案 2 :(得分:0)

您的输入高于Java int的限制,即2,147,483,647。 即使您将其更改为long,您也无法转换高于1000000000000000000的值(十进制等于262144)。最佳解决方案是通过逐个字符计算而不转换整个字符串。

因此,请尝试以下代码,

public static long convert(String binary) {
    long pow = 1, decimal = 0;
    for (int i = (binary.length() - 1); i >= 0; i--) {
        if (binary.charAt(i) == '1') {
            decimal += pow;
        }
        pow *= 2;
    }
    return decimal;
}

答案 3 :(得分:0)

为什么先将它转换为十进制?这很简单:

   public static void main( String[] args ) {
      String str = "10011010010";
      int len = str.length();
      long mult = 1;
      long val = 0;
      for (int i = len - 1; i >= 0; i--) {
         if ( str.charAt( i ) == '1' ) {
            val += mult;
         }
         mult *= 2;
      }
      System.out.println( val );
   }
相关问题