我的代码输出(从十进制到二进制的转换代码)似乎有问题。如果输入一个数字(例如12),它将输出01100。我只希望它输出1100(开头没有0)。有什么我可能想念的吗?先感谢您!这是我的代码如下:
import java.util.*;
public class DtoB{
public static void main(String[] args){
Scanner in = new Scanner(System.in);
System.out.print("Enter a positive integer: ");
int number = in.nextInt();
int i;
int j;
int[] binary = new int[10];
if ( number > 0 ){
for (i = 0; number != 0; i++){
binary[i] = number % 2;
number /= 2;
}
for ( j = i; j >= 0; j-- ){
System.out.print(binary[j]);
}
System.out.print(" is the binary conversion of your integer.");
} else {
System.out.print("Error: You have not entered a positive integer.");
}
}
}
用i-1初始化j
for ( j = i-1; j >= 0; j-- ){
System.out.print(binary[j]);
}