我的程序应该把十进制数转换成二进制数。对于大数字,它会给我一个负数,而不是二进制数。为什么会这样呢?
例如,如果我提供2321,我会得到100100010001,这是可以接受的。但是如果我提供241242141,我就会得到-2127232070093227171。
我不能使用字符串,数组,函数。如果不定义为字符串,还有其他选项吗?输出是什么?
import java.util.Scanner;
public class d {
public static void main(String[] args) {
long num = 0;
long temp = 0L;
Scanner sc = new Scanner(System.in);
num = sc.nextLong();
long place = 1L;
long output = 0;
//System.out.print(""+ num%2+ (num%2)%2);
while(num != 0) {
temp = num % 2;
num = num / 2;
output += (place*temp);
place *=10;
}
System.out.print(""+output);
}
}发布于 2012-11-06 19:08:26
你的问题在这里
output += (place*temp);
place *=10;这会产生一个溢出的数字。
一种简单的替代方法是创建一个字符串,而不是生成一个无论如何都要转换为字符串的数字。
StringBuilder output = new StringBuilder();
while(num != 0) {
output.append(num & 1);
num >>>= 1;
}
System.out.print(output.reverse()); 甚至是
StringBuilder output = new StringBuilder();
for(long num = sc.netLong(); num != 0; num >>>= 1)
output.append(num & 1);
System.out.print(output.reverse()); 如果您只想使用input或output函数,则为。
long num = 241242141;
int shift = 63;
while (num >>> shift == 0 && shift > 0) shift--;
for (; shift >= 0; shift--)
System.out.print((num >>> shift) & 1);
// for comparison only
System.out.println("\n"+Long.toBinaryString(num));打印
1110011000010001000000011101
1110011000010001000000011101发布于 2012-11-06 19:10:11
问题是,您将Binary Equivalent存储在long type中,它不能存储这么长的值。
您应该使用StringBuilder并将您的remainder - temp附加到其中。然后反转打印出来:
StringBuilder builder = new StringBuilder();
while(num != 0) {
temp = num % 2;
num = num / 2;
builder.append(temp);
output += (place*temp);
place *=10;
}
System.out.println(builder.reverse());如果您不需要使用任何methods,那么只需使用String Concatenation,然后使用一个循环反向打印字符串:-
String builder = "";
while(num != 0) {
temp = num % 2;
num = num / 2;
builder += temp;
output += (place*temp);
place *=10;
}
for (int i = builder.length() - 1; i >= 0; i--) {
System.out.print(builder.charAt(i));
}但是,请注意,这将在Heap上创建大量的String objects。另外,这里使用的是charAt方法,您必须使用该方法。
发布于 2012-11-06 19:20:42
使用递归:
public class d {
static void toBinaryString( long number )
{
if( number > 1 ) toBinaryString( number / 2L );
System.out.print( number % 2L );
}
public static void main(String[] args) {
long num = 241242141L;
System.out.println( Long.toBinaryString( num ));
toBinaryString( num );
}
}输出:
1110011000010001000000011101
1110011000010001000000011101https://stackoverflow.com/questions/13249419
复制相似问题