finding the largest digit in an integer using recursion - java

I have a practice who's task is to find the largest digit in an integer using recursion in java. For example, for the number 13441 the digit '4' will be returned.
I have been trying for a day now and nothing worked.
What I thought could work is the following code, which I can't quite get the "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 you can see it's completely wrong.
Any help would be great. Thank you

This works by recursively comparing the right most digit with the highest digit of the remaining digits (those being obtained by dividing the original number by 10):
int maxDigit(int n) {
n = Math.abs(n); // make sure n is positive
if (n > 0) {
int digit = n % 10;
int max = maxDigit(n / 10);
return Math.max(digit, max);
} else {
return 0;
}
}

The simplest base case, is that if n is 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 and
// maxDigit of the rest
}
or, slightly more concise;
public static int maxDigit(int n){
return n==0 ? 0 : Math.max(n%10, maxDigit(n/10));
}

I won't dig into your code, which I think is more complicated than it has to be. But it seems to me that the cases are actually fairly simple (unless I'm missing something):
base case: parameter only has one digit, return that one digit as parameter
general case: return whichever is higher of (the first digit in the parameter) and (the maxDigit of the remaining digits in the parameter)

You may also write:
public static int maxDigit(int n, int max){
if(n!=0) {
if(n%10 > max) {
max = n%10;
}
return maxDigit(n/10, max);
}
return max;
}

This is the solution.
public static int maxDigit(int n, int max){
if (n!=0){
if ( n%10 > max){
max = n%10;
return maxDigit(n/10,max);
}else{
return maxDigit(n/10,max);
}
}
return max;
}

Related

Printing number using recursion in java without its biggest digit

Using recursion I need to input a number and the console will print this number without its highest digit. If it's smaller than 10 it will return 0.
I already found the biggest digit but how can i remove it and print the number without it after?
This is the code for the biggest digit:
public static int remLastDigit(int n){
if(n==0)
return 0;
return Math.max(n%10, remLastDigit(n/10));
}
If i input 12345 i expect the output to be 1234. if i input 9 or less i expect the output to be 0.
Here is my solution:
// call this method
public static int removeLastDigit(int number) {
return removeLastDigitImpl(number, largestDigit(number));
}
private static int removeLastDigitImpl(int number, int largestDigit) {
if (number < 10) { // if the number is a single digit, decide what to do with it
if (number == largestDigit) {
return 0; // if it is the largest digit, remove it
} else {
return number; // if it is not, keep it
}
}
// handle the last digit of the number otherwise
if (number % 10 == largestDigit) {
// removing the digit
return removeLastDigitImpl(number / 10, largestDigit);
} else {
// not removing the digit
return removeLastDigitImpl(number / 10, largestDigit) * 10 + number % 10;
}
}
// this is the same as your attempt
private static int largestDigit(int n){
if(n==0)
return 0;
return Math.max(n%10, largestDigit(n/10));
}
Since you've already found the max digit nicely, here's how you can print the number without it.
public static void main(String[] args) {
printWithoutDigit(2349345, remLastDigit(2349345));
}
public static void printWithoutDigit(int number, int maxDigit) {
Integer.toString(number).chars().filter(digit -> Integer.valueOf(String.valueOf((char)digit))!=maxDigit).forEach(d -> System.out.print((char)d));
}
You could convert your number to a String, or more precisely to a char-array. Then, you can find out where in this array the biggest digit is, remove it and convert your char-array back to an integer.
This would roughly look like this:
int num = 12345; //the number from which you want to remove the biggest digit
char[] numC = String.valueOf(num).toCharArray();
int biggestDigit = 0;
int biggestDigitIndex = 0;
for (int i = 0; i < numC.length; i++) {
if (biggestDigit < Character.getNumericValue(numC[i])) {
biggestDigit = Character.getNumericValue(numC[i]);
biggestDigitIndex = i;
}
//Remove digit at index biggestDigitIndex from numC
//Convert numC back to int
}
Of course, you have to incorporate this into your recursion, which means returning the number you got after converting numC back to int and then feed this into your input parameter again. Also, of course you need to add a check if your number is < 9 in the beginning.

How to exit from a method, i.e how can i return from a function in this recursion in java?

How to exit from a method, i.e how can i return from a function in this recursion in java?
public class solution {
public static int countZerosRec(int input){
int n=0;
int k =0;
int count=0;
//Base case
if(n==0)
{
return; // How can i return the method from here, i.e how can i stop the execution of the recursive program now.
}
k=input%10;
count++;
n=input/10;
countZerosRec(n);
int myans=count;
return myans;
}
}
Please help me getting out of this method.
This is a program to count number of zeroes.
Example, 34029030 ans = 3
You can try below approach:
public class MyClass {
public static void main(String args[]) {
System.out.println("total zeroes = " + returnZeroesCount(40300));
}
public static int returnZeroesCount(int input){
if(input == 0)
return 0;
int n = input % 10;
return n == 0 ? 1 + returnZeroesCount(input / 10) : returnZeroesCount(input / 10);
}
}
How it works: Assuming your input > 0, we try to get the last digit of the number by taking the modulus by 10. If it is equal to zero, we add one to the value that we will return. And what will be the value that we would be returning? It will be the number of zeroes present in the remaining number after taking out the last digit of input.
For example, in the below case, 40300: we take out 0 in first step, so we return 1+number of zeroes in 4030. Again, it appears as if we have called our recursive function for the input 4030 now. So, we again return 1+number of zeroes in 403.
In next step, since last number is 3, we simply return 0+total number of zeroes in 40 or simply as total number of zeroes present in 40 and so on.
For ending condition, we check if the input is itself 0. If it is zero then this means that we have exhausted the input number and there are no further numbers to check for. Hence, we return zero in that case. Hope this helps.
If your main focus is to find number of zeroes in a given number , You can use this alternatively:
int numOfZeroes =0;
long example = 670880930;
String zeroCounter = String.valueOf(example);
for(int i=0; i< example.length();i++){
if(zeroCounter.charAt(i) ==0){
numOfZeroes++;
}
}
System.out.print("Num of Zeros are"+ numOfZeroes);` `
Instead of posting a code answer to your question, I'll post a few pointers to get you moving.
As #jrahhali said, as your code is, it'll not get past the return
statement inside the if block(which is an error BTW, because you have an int return
type).
I'd recommend that you move the last two lines to some calling
function(such as a main method). That way all this function will
need to do is do some basic processing and move forward.
You aren't checking k at all. As it is, your count is going to
always increment.
Hope this much is enough for you to figure things out.
int count =0;
private int getZeroCount(int num){
if(num+"".length == 1){
if(num==0){
count++;
}
return count;
}
if(num%10 == 0){
count++;
}
num /= 10;
getZeroCount();
}
Method1 :
public static int countZero1(int input) {
int count = 0;
//The loop takes the remainder for the value of the input, and if it is divided by 10, then its number of digits is 0.
// When the value of the input is less than 0, the cycle ends
while (input >0){
if (input % 10 == 0){
count ++;
}
input /= 10;
}
return count;
}
Method2 :
private static int count = 0;
public static int countZero2(int input) {
//Recursive call function
if (input % 10 == 0){
count ++;
}
input /= 10;
if (input <= 0){
return count;
}else {
return countZero2(input);
}
}

Finding minimum number in an array with recursion [duplicate]

This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Find maximum value in an array by recursion
(5 answers)
Closed 6 years ago.
when i dissect the logic of my code, it makes sense to me and looks like it should work. I need to find and return the smallest number in an array using recursion. here is my code
public static int findMin(int[] numbers, int start, int last)
{
int min = numbers[start]; // sets first value in array to minimum
if(numbers[start]<numbers[last]&& numbers[start]<min)
{ // if 1st value < last value in array and 1st value smaller than min, set min to first value
min = numbers[start];
}
else if(numbers[start]>numbers[last]&& numbers[last] < min)
{ // if 1st value > last value and last value < min, set min to last value
min = numbers[last];
}
else
{ // if 1st and last value are equal returns 1st value
return numbers[start];
}
// recursively calls... or not
findMin(numbers, start+1, last-1);
return min;
}
inputs used are 33
-55, -44, 12312, 2778, -3, -2, 53211, -1, 44, 0
output getting:
The minimum number is 0
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1
at Assignment9.countEven(Assignment9.java:72)
at Assignment9.countEven(Assignment9.java:87)
at Assignment9.main(Assignment9.java:34)
Expected: -55
i am assuming my recursive call is incorrectly placed. Please help, thank you.
This should do the trick
public static int findMin(int[] numbers, int start, int last)
{
if(start == last) return numbers[0];
return Math.min(numbers[start],findMin(numbers, start+1, last));
}
If for some reason you cannot use the Math.min you can always use:
public static int findMin(int[] numbers, int start, int last)
{
if(start == last) return numbers[0];
int min = findMin(numbers, start+1, last);
return (numbers[start] <= min) ? numbers[start] : min;
}
The major problems with or solution are:
-> you are not correctly checking the stop case;
-> you are not using the min value calculated in each recursive call;
-> and you are not checking for the cases that you go over the array limits.
First glance, it looks like you are not saving the result from your recursive call, you're just calling it as if it was a void method.
Instead of
findMin(numbers, start+1, last-1);
return min;
Try:
min = findMin(numbers, start+1, last-1);
return min;
Why don't you simple try this:
public static int findMin(int[] numbers, int start, int last) {
if(start == last){
return numbers[start];
}
if(numbers[start] <= numbers[last]) {
last -= 1;
} else {
start += 1;
}
return findMin(numbers, start, last);
}
OR you can use Divide and Conquer strategy as suggested by Qriss:
public static int findMin(int[] numbers){
return findMinHelper(numbers, 0, numbers.length);
}
public static int findMinHelper(int[] numbers, int left, int right){
int min1 = 0, min2 = 0;
if (left == right - 1){
return numbers[left];
} else {
min1 = findMinHelper(numbers, left, (right + left) / 2);
min2 = findMinHelper(numbers, (right + left) / 2, right);
}
return (min1 < min2) ? min1 : min2;
}

How to find greatest digit in a number using recursion?

I am trying to write a function in Java that returns the greatest digit in a number using recursion.
I have managed to do it using two parameters, the number and greater digit.
Initially the greater digit parameter accepts value as 0.
static int getGreatestDigit(int num , int greater){
if(num != 0){
if(num %10 > greater){
greater = num%10;
num = num/10;
return getGreatestDigit(num , greater);
}else{
num = num/10;
return getGreatestDigit(num , greater);
}
}
return greater;
}
I want to write same recursive function but with only one parameter that is number.
Like
int getGreatestDigit(int num){
//code
}
I am stuck at logic. How to do that?
Only the first call to getGreatestDigit(num) needs to keep track of the greater result. Each recursive call to getGreatestDigit(num) will return the greatest digit in the part of the original number that it is tasked with scanning. The very first invocation of getGreatestDigit(num) can compare the number it took with the greatest number returned from all recursive calls.
int getGreatestDigit(int num)
{
if (num == 0) return 0;
int lastNum = num % 10;
int otherDigits = num / 10;
int recursiveLastNum = getGreatestDigit(otherDigits);
return Math.Max(lastNum, recursiveLastNum);
}
static int getGreatestDigit(int num)
{
return num == 0 ? 0 :
Math.Max(num % 10, getGreatestDigit(num / 10));
}
So basically, you look at the least significant digit each time, comparing it against the maximum of the rest of the digits.
You can do this, if you use the functions stack as temporary memory to hold your interim results, i.e. what was previously stored in the greater parameter.
This changes your function to be no longer tail recursive, making it worse performance wise.
int greatestDigit(int num) {
int last = num % 10;
int rest = num / 10;
if (rest == 0) {
return last;
} else {
int candidate = greatestDigit (rest);
if (candidate > last) {
return candidate;
} else {
return last;
}
}
}
/** Pseudocode:
1. if num > 9, /10 and call getGreatestDigit on that (recursive step). Then get the current digit (undivided) and return the greater of the two
2. if num <= 9, return num
*/
int getGreatestDigit(int num){
//code
}
package Map;
import java.util.ArrayList;
public class Practice8 {
public int highestDigit(int number){
ArrayList<Integer> temp= new ArrayList<>();
StringBuilder sb= new StringBuilder();
sb.append(number);
String value= sb.toString();
for(int i=0;i<value.length();i++){
temp.add((int)value.charAt(i)-'0');
}
int max=0;
for(int x: temp){
if(x>max){
max=x;
}
}
return max;
}
public static void main(String[] args) {
Practice8 practice8= new Practice8();
System.out.println(practice8.highestDigit(379));
}
}

Java - Number of occurrences of a digit in a number without loop

Given a non-negative int n, how do i return the count of the occurrences of a digit e.g 7, so for example 717 yields 2? (no loops). Here is my code but it doesn't work well.
public int count7(int n) {
int count = 0;
if(n==7){
count++;
return count;
}
else if(n>7 && n<100)
return count7(n/10)+count7(n%10);
else if( n>100)
return count7(n/10)+count7(n%10);
else return 0;
}
Your code seems like it should be working. Not sure what you mean by "doesn't work well".
Here is an a bit cleaner/shorter version of the same solution:
int count7(int n) {
if(n == 0) return 0;
return (n%10 == 7 ? 1 : 0) + count7(n/10);
}
For the fun of it:
public static int count7( int n ) {
return Integer.toString( n )
.replaceAll( "[^7]" , "" )
.length();
}
Probably better fits to code golf ,-)
Here is a solution :
public int count(int number, int digit){
String numberToString = new Integer(number).toString();
String digitToString = new Integer(digit).toString();
return StringUtils.countMatches(numberToString,digitToString);
}
It will count for you how many digit are in number
So count(717,7) will return 2
A fast solution :
return Integer.toString(n).split("7").length-1;
When you want to look at the digits in the decimal representation of a number, it's usually reasonable to let the already available and optimized number stringification function do the job (that is Integer.toString(yournumber)). Of course there are loops behind, but there's even loops in the implementation of your recursive calls...

Categories