java - Recursive method that prints all of the digits in a number that or greater than the first digit and lower than the last digit -
the problem:
i'm trying write recursive method prints of digits in number or greater first digit , lower last digit. accomplished write recursive method prints of digits or lower last digit. can't figure out how check if digit grater first digit.
examples:
for print(325648) print 5, 6, 4.
for print(237) print 3.
for print(925648) not print digit.
this code:
public static void print(int n) { print(n,n%10); } private static void print(int n,int lastdigit) { if(n==0) return; if(n%10<lastdigit) system.out.println(n%10); print(n/10,lastdigit); }
the requirement of method:
- not allowed use loops(or methods loops).
- allowed use 1 recursive transition.
- the length of number not known.
- the method can change number, @ end of operation number should same @ beginning.
please note: not homework assignment! i'm writing method practice exam talking tomorrow.
the idea here recurse dividing 10 until number reduced first digit. on return through recursions have first digit return value , compare quite easily.
private static void print( int n ){ print( n/10, n%10 ); } private static int print( int n, int ld ){ if( n < 10 ) return n; int digit = n % 10; int first = print( n/10, ld ); if( digit < ld && digit > first ) system.out.println( digit ); return first; }
Comments
Post a Comment