基础解法:输入一个数,将其变成二进制输出。这种做法的输入数个数提前得先规定好
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
String str = "";
if(n==0)
System.out.println(0);
while(n!=0){
str = n%2+str;
n = n/2;
}
System.out.println(str);
}
}
然而这道题的难点在于,输入多少个数是不确定的。
其他人给出的解法有一种比较简短的
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigInteger;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
String s;
while ((s = bf.readLine()) != null) {
BigInteger bigInteger1=new BigInteger(s);
System.out.println(bigInteger1.toString(2));
}
bf.close();
}
}
我开始以为在验证时输入要像样例一样一行一个数字 最后发现一旦换行就会执行,但这种代码也是通过的,还是不能太刻板。