java将int整数转化为int数组,不用转String。

键盘输入整数,得到整形数组,正序,逆序

public class Main{
       	public static void emm(){ 
                 Scanner sc = new Scanner(System.in);
                 int q = sc.nextInt();
                 int temp = q;//输入的整数
                 int wei = 0;//几位数
                 //算出位数
                 while(temp!=0){
                        temp = temp/10;
                        wei++;
                 }
        			
    			//输出结果
    			//位数
                System.out.println("位数:"+wei);
                //顺序输出
                get(q,wei);
                System.out.println();
                //逆序输出
                back(q,wei);
            }
             //顺序输出的方法
            public static void get(int num,int wei){
                int tmp = num;
                 //创建一个和整数位数相同大小的数组
                int[] element = new int[wei];
                
                System.out.print("分别是:");
                for(int i = wei;i>0;i--){
                	//从高位到低位依次取数字
                    int m1 = (new Double(Math.pow(10,i-1))).intValue();
                    tmp = (num/m1)%10;
                    System.out.print(tmp+" ");
                }
            }
    		//逆序输出的方法
            public static void back(int num,int wei) {
                Double tmp = Double.valueOf(num);
                //创建一个和整数位数相同大小的数组
                int[] element = new int[wei];
                System.out.print("逆序是:");
                //获取逆序存入数组element中
                for(int i = 1;i<=wei;i++){
               		 //从低位到高位依次取数字
                    tmp = (num%Math.pow(10,i))/Math.pow(10,i-1);
                    int m1 = (new Double(tmp)).intValue();
                    System.out.print(m1+" ");
                }
            }
    	public static void main(String[] args) {
            //sushu();
            //sushu100();
            sum();
            //shui();
            //emm();
            //fen();
        } 
}

运行结果:
在这里插入图片描述

关键的是这两句:
正序:
34567
1…34567 / 10^5 = 3 , 3 % 10 =3
2…34567 / 10^4 = 34, 34 %10 =4
以此类推
tmp = (num/ (new Double(Math.pow(10,i-1))).intValue(); )%10;
最后得到3 4 5 6 7存入数组

逆序:
1…34567 % 10^1 =7 , 7 / 10^0 = 7
2…34567 % 10^2 =67, 67 / 10^1 = 6
以此类推
tmp = (num%Math.pow(10,i))/Math.pow(10,i-1);
最后得到7 6 5 4 3存入数组

猜你喜欢

转载自blog.csdn.net/weixin_40879743/article/details/88829101