方法一:通过Integer.toBinaryString(int);
public class DecimalToBinary {
public static void main(String[] args) {
System.out.println(Integer.toBinaryString(5));
}}
方法二:自己写
package GeneticAlgorithm;
import java.util.Stack;
public class DecimalToBinary {
public static void main(String[] args) {
//方法一:直接用Integer.toBinaryString(int)
System.out.println(Integer.toBinaryString(5));
//方法二:自己写
System.out.println(toBinary(15));
}
public static String toBinary(int a) {
String str = "";
Stack s = new Stack();
while (a != 0) {
s.push(a % 2);
a = a / 2;
}
while (!s.empty()) {
str += s.pop();
}
return str;
}
}