A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

类名可以随便改,写的不好 勿喷! 如果能赏点黑马币 哈哈 完美!
public class Test8 {
        static ArrayList<Integer> al = new ArrayList<>();                  //该集合记录除以2的余数
        public static void main(String[] args) {
                print();
        }
        public static void print(){
                Scanner sc = new Scanner(System.in);
                int num = 0;
                while(true){                       
                        System.out.println("请输入一个数字的字符串,然后我们会把它转换为十进制整数:");
                        String str = sc.nextLine();
                        try {
                                num = Integer.parseInt(str);
                                break;
                        } catch (Exception e) {
                                try {
                                        new BigInteger(str);
                                        System.out.println("您录入的位数太多,请重新录入:");
                                } catch (Exception e2) {
                                        try {
                                                new BigDecimal(str);
                                                System.out.println("你您录入的是一个小数,请重新录入:");
                                        } catch (Exception e3) {
                                                System.out.println("错误,您录入的是非法字符!请重新录入:");
                                        }
                                }
                        }
                }
                if(num != 0){
                        change2(num);
                        fList();
                        System.out.print("转换为二进制为:");
                        for(int n : al){
                                System.out.print(n);
                        }
                }
        }
       
        public static void change2(int n){
                if(n==1||n==0){
                        al.add(n);
                }else{
                        al.add(n%2);
                        change2(n/2);
                }       
        }
        //集合取反
        public static void fList(){
                int temp;
                for(int i=0;i<al.size()/2;i++){
                        temp = al.get(i);
                        al.set(i, al.get(al.size()-i-1));
                        al.set(al.size()-i-1, temp);
                }
        }
}


0 个回复

您需要登录后才可以回帖 登录 | 加入黑马