java - 二进制转换为十进制的输出不是预期的?

标签 java string

Given a binary number as input convert it into base 10 (decimal system). Note that to convert a number 100111 from binary to decimal, the value is 1*2^5 + 0*2^4 + 0*2^3 + 1*2^2 + 1*2^1+ 1*2^0. Also note that 5 here is the length of the binary number.

我的方法

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

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

I am getting a wrong Ans on the last test case. Can anyone guide me what is wrong in my code.?

下面是我的代码:

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

最佳答案

整数的最大值是 (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;
    }  

关于java - 二进制转换为十进制的输出不是预期的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34139242/

相关文章:

javascript - 由逗号分隔 N 次的一系列数字的正则表达式

python - 如何从python中的文本文件中获取子字符串?

.net - 为什么 .NET 区分字符串和字符?

java - 如何用始终在最上面的对话框结束 Swing 程序?

java - 在 Activity 中调用 Runnable 类

java - 集合如何在内部避免重复?

java - 在 hibernate +Java 中迭代对象列表时出错?

java - 如何阻止我的 do while 循环接受除 "stop"之外的每个字符串

c# - 在字符串列表中查找子字符串

java - isAnonymous() 和 isAuthenticated() 都返回 false