求整数各位上的数字

Description

给出一个不多于5位的正整数,要求 1、求出它是几位数 2、分别输出每一位数字 3、按逆序输出各位数字,例如原数为321,应输出123

Input

一个不大于5位的正整数(无前导零)

Output

三行第一行 位数第二行 用空格分开的每个数字,注意最后一个数字后没有空格第三行 按逆序输出这个数

Sample Input

12345

Sample Output

5
1 2 3 4 5
54321

思路

将输入的数字转化为字符串,运用Integer.toString方法,然后遍历时使用charAt()进行遍历

import java.util.Scanner;
public class Main_test {
    public static void main(String[] args){
        Scanner sc=new Scanner(System.in);
        int n=sc.nextInt();
        String str=Integer.toString(n);
        System.out.println(str.length());
        for(int i=0;i<str.length();i++){
            char it=str.charAt(i);
            if(i<str.length()-1)
            System.out.print(it+" ");
            else
                System.out.print(it+"");
        }
        System.out.println();
        for(int i=str.length()-1;i>=0;i--){
            char ut=str.charAt(i);
            System.out.print(ut);
        }
    }

}

在编程过程中应该注意到最后一次的数字没有空格应该运用if判断输出,不然不能ac

猜你喜欢

转载自blog.csdn.net/MimosaX/article/details/86568158