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/