recursive function digits of a positive decimal integer in reverse order c++

前端 未结 5 556
清歌不尽
清歌不尽 2021-01-21 18:22

I have an assignment to write a recursive function that writes the digits of a positive integer in reverse order. My problem is that the function doesn\'t display the reverse co

5条回答
  •  感动是毒
    2021-01-21 18:39

    int rev(int n) {
        if(n<10&&n>-10) return n;
    
        int length=0;
        for (int i=n; i; i/=10) length++;
    
        return n%10*(int)pow(10, length-1) + rev(n/10);
    
    }
    

    Here's my solution. It takes only one parameter and return an int. Also don't forget to include cmath.

    int intLength(int i) {
        int l=0;
        for(;i;i/=10) l++;
        return l;
    }
    
    int rev(int n) {
        return n<10&&n>-10 ? n : n%10*(int)pow(10, intLength(n)-1) + rev(n/10);
    }
    

    Or this way it's a bit more elegant.

提交回复
热议问题