Recursion - digits in reverse order

前端 未结 15 1071
一向
一向 2021-01-15 10:32

I need to implement a recursive method printDigits that takes an integer num as a parameter and prints its digits in reverse order, one digit per line.

This is what

15条回答
  •  南笙
    南笙 (楼主)
    2021-01-15 10:42

    //Reverse a number using recursion by bibhu.rank
    public class Rev_num {
        public static int revnum(int x){
            int temp1=x,temp2=1;
            if(x<10){
                return x;
            }
            while(temp1>=10){
                temp2*=10;
                temp1/=10;
            }
            if(((x%temp2) < (temp2/10))&& x%temp2!=0){
                int c=temp2;
                while(c> x%temp2){
                    c/=10;
                }
                c=temp2/c;
                temp2=x%temp2;
                return((temp1)+(c*revnum(temp2)));
            }
            temp2=x%temp2;
    
            return (temp1+(10*revnum(temp2)));
    
        }
    
        public static void main(String[] args) {
            // TODO Auto-generated method stub
            System.out.println("Enter a number");
            Scanner y=new Scanner(System.in);
            System.out.println(revnum(y.nextInt()));
            y.close();
    
    
        }
    
    }
    

提交回复
热议问题