java - finding the largest digit in an integer using recursion -
i have practice who's task find largest digit in integer using recursion in java. example, number 13441 digit '4' returned.
i have been trying day , nothing worked.
what thought work following code, can't quite "base case" for:
public static int maxdigit(int n) { int max; if (n/100==0) { if (n%10>(n/10)%10) { max=n%10; } else max=(n/10)%10; } else if (n%10>n%100) max=n%10; else max=n%100; return maxdigit(n/10); }
as can see it's wrong.
any great. thank you
the simplest base case, if n 0, return 0.
public static int maxdigit(int n){ if(n==0) // base case: if n==0, return 0 return 0; return math.max(n%10, maxdigit(n/10)); // return max of current digit , // maxdigit of rest }
or, more concise;
public static int maxdigit(int n){ return n==0 ? 0 : math.max(n%10, maxdigit(n/10)); }
Comments
Post a Comment