0
点赞
收藏
分享

微信扫一扫

打印输入的数是几位数,并且倒叙打印每一位

若如初梘 2022-04-13 阅读 84
java

面试题连函数提示都没给,给出问题,结果,编写程序,给定一个n(n<=5)位数,判断它是几位数,倒叙输出每一位,错一点都编译不成功
示例: 1247 4 7 4 2 1

public class Test1 {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int count = printNum(sc.nextInt());
        System.out.print(count+" ");
        for(int i = 0; i < count; i++){
            System.out.print(array[i]+" ");
        }
        System.out.println();
    }
    //考虑到这个数不会超过5,数组大小可以给到5
    static int[] array = new int[5];
    public static int printNum(int n){
        //通常都会使用%来求每一位的数,123%10 3  12%10 2 1%10 1  分别求出了倒叙的每一位
        //有了这个推理逻辑,就可以写出循环了,注意到循环的边界条件
        //考虑到需要求这个数的位数,给定一个变量,每循环一个变量+1,最后返回变量的值就是这个数的位数
        int count = 0;
        while(true){
            int temp  = n%10;
            //如果在这里面打印temp的话,会造成结果为 7 4 2 1 4,需要使用到一个数据保存每一位数
            if(temp != 0)array[count++] = temp;
            n/=10;
            //结束条件不能是n/10 == 0,yin为会少执行一次,但是n最后会变为0
            if(temp == 0) return count;
        }
    }
}

写到这就基本写完了,但是考虑到如果输入的是0,不会打印0 0,所以可以加上if(n == 0) array[count++] = 0;

举报

相关推荐

0 条评论