publicclassMain{publicvoidchangeTenToTwo(int n){
String num ="";while(n !=0){int res = n %2;
num = res + num;
n /=2;}int binNum = Integer.parseInt(num);
System.out.println(binNum);}publicstaticvoidmain(String[] args){
Main m =newMain();
m.changeTenToTwo(45);}}
2.拆分法,将十进制整数转换为多个二进制权重之和
publicclassMain{publicvoidchangeTentoTwo(int N){
ArrayList<Integer> arr =newArrayList<>();
ArrayList<Integer> cmp =newArrayList<>();int i =0, tmp =0;// 使用一个死循环while(true){
tmp =(int) Math.pow(2, i);if(tmp <= N){
arr.add(tmp);}else{break;}++i;}int num = N;// 判断由哪些二进制的权重构成 从高到低判断for(--i; i >=0;--i){if(num >= arr.get(i)){
cmp.add(1);
num -= arr.get(i);}elseif(num < arr.get(i)){
cmp.add(0);}}for(Integer t : cmp){
System.out.print(t);}}publicstaticvoidmain(String[] args){
Main m =newMain();
m.changeTentoTwo(45);}}