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

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...

Related

JAVA: Fibonacci Recursive and Non-Recursive Function

Hi there sorry for this noob question. I'm Mario and may I ask if my program is correct for recursive and non-recursive function for Fibonacci Secquence nth Value.
static int recursiveMethod(int num)
{
if (num <= 1)
return num;
return recursiveMethod(num-1) + recursiveMethod(num-2);
}
static int nonRecursiveMethod(int num) {
if (num == 0) {
return 0;
}
if (num == 1) {
return 1;
}
int first = 0;
int second = 1;
int nth = 1;
for (int i = 2; i <= num; i++) {
nth = first + second;
first = second;
second = nth;
}
return nth;
}
For summary:
Example I inputted 6 as my nth value. Then the outputs are
RECURSIVE: 8 then
NON-RECURSIVE: 1 1 2 3 5 8
Is that correct?
Calling nonRecursiveMethod will produce the same output as calling recursiveMethod. The result is correct, recursiveMethod is inefficient for big numbers, though, because it will compute results for lower numbers again and again.
yeah both the approaches are fine. What I would like to suggest here is rather than calling function for every "num" you can pre-compute and store the values(Dynamic Programming).

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);
}
}

Java recursion 1234 to 4321 for example

I have a question how to better tackle this task, I have a version, but I am sure there is a better and shorter way to do this maybe. I need to take any int number(return it as an int without turning it into a String), but never with a 0 at the end (100, 120) but like 1234, or 4132. I need to take this number and using recursion rewrite it the other way around example 1234 to 4321, 4132 to 2314, maybe there is a way this is called, i personally don't know about it.
Here is what I got:
public static int reverse(int r, int n, int k){
if(r==0)
return 0;
else
return + (r%10) * (int)Math.pow(10, (n-k-1))+reverse (r/10, n, k+1)
}
public static void main(String[] args) {
System.out.println(reverse(1234, 4, 0));
}
Working with a String representation of the int may make the code more readable.
Try:
Integer.parseInt(new StringBuilder(r+"").reverse().toString());
Current code doesn't compile. Added a ) to this line:
from if(r==0{ change to if(r==0){
and added a ; in this line return + (r%10) * (int)Math.pow(10, (n-k-1))+reverse (r/10, n, k+1);
Your code after this two changes will look like:
public static int reverse(int r, int n, int k){
if(r==0)
{
return 0;
}else{
return + (r%10) * (int)Math.pow(10, (n-k-1))+reverse (r/10, n, k+1);
}
}
if the number ends with 0, the program will not show any special message to the user, i.e 1230 will return 321. In this case, maybe
maybe print a message ("number must not end with a 0) or throw an exception?
Didn't notice the recursion part.
public static void main(String[] args) {
int i = 589;
System.out.println(reverse(i));
}
public static int reverse(int k){
if(k/10 == 0){return k;}
else return (k%10 * (int)Math.pow(10, (int)Math.log10(k))) + reverse(k /10);
}
Explanation:
k%10 gives you the last digit of an int
(int) (Math.log10(k)) returns
number of Digits in an Integer minus one
public static final int reverse(int number) {
final int lastDigit = number % 10;
final int length = (int) Math.log10(number);
return (number < 10) ? number : (int) (Math.pow(10.0, length) * lastDigit + reverse(number / 10));
}
If the number is lower then 10 it's the number itself. Otherwise it's the last digit multiplied with 10^n where n is the length of the number, so it's now at the position for the first digit.
Then add the result of a reverse of the rest number to it (the number without the last digit).
You take advance of the recursion function itself as it would already work to solve the big problem. You only have to think about the trivial end condition and one single step (which mostly is something you would suggest as the last step)
This is the best way that I could make it using recursion and without conversions.
private static int myReverse(int n, int r) {
if(n == 0)
return r;
int newR = r*10 + n%10;
return myReverse(n/10, newR);
}
What I'm doing here is:
Two parameters: n - the number you want to reverse, r - the reversed number
The recursion stops when n equals 0 because it always dividing it by 10
newR - This variable is unnecessary but it´s better for 'understanding' porposes, first I multiply r by 10 so I can sum the last value o n. For example, reverse 123: along the way if r = 12 and n = 3, first 12*10 = 120, n%10 = 3 then r*10 + n%10 = 123
A 'pleasant' way with only one return statement:
private static int myReverse2(int n, int r) {
return n == 0 ? r : myReverse2(n/10, r*10 + n%10);
}

Euler 14. Answer doesn't match

public class problem14 {
public static void main(String[] args) {
int biggest = 0;
int biggestNum =0;
for(int i = 1; i<1000001;i++){
if(Solve(i)>biggest){
biggest = Solve(i);
biggestNum = i;
}
}
System.out.println("Chain: " + biggest + "Number: " + biggestNum);
}
public static boolean evenorodd(int num){
//returns true if even, and returns false if odd
int lastNum = num % 10;
if(lastNum==0||lastNum==2||lastNum==4||lastNum==6||lastNum==8){
return true;
}else{
return false;
}
}
public static int Solve(int num){
int count = 1;
int end = 0;
while(end!=1){
if(evenorodd(num)){
num = num/2;
count+=1;
if(num==1){
end=1;
return count;
}
}
if(!evenorodd(num)){
num = 3*num +1;
count+=1;
if(num==1){
end=1;
return count;
}
}
}
return count;
}
}
Sorry guys, I already look up those problem 14 solutions, and I still couldn't figure out why my code doesn't give me the right answer. Please help me, I have trying to figure out for almost a hour now. I just need to know why I am not getting the right answer, since I have been testing out a lot of numbers.
The problem with your algorithm is that in your Solve() method,you are checking if(evenorodd(num)) and if(!evenorodd(num)) separately! Because of this even in case,if your num is even and is processed to yield true result but num becomes 1 at last,and hence it is also getting processed by if(!evenorodd(num)) because it has turned 1 // an odd number.
Second,instead of directly returning count from if-else block,you should better use break statement for exiting the loop and finally returning count!
Try reducing it to if(evenorodd(num)){...} else {...}.
Workout for your int Solve(num) method to ease your effort :-
public static int Solve(int num){
int count = 1;
int end = 0;
while(end!=1){
if(evenorodd(num)){
num = num/2;
count+=1;
if(num==1){
end=1;
break;
}
}
else
{
num = 3*num +1;
count+=1;
if(num==1){
end=1;
break;
}
}
}
return count;
}
I hope it helps and you obtain the correct answer! BEST WISHES...
Your algorithm is fine. You're blowing out on the range of an int. Use longs instead.
A Groovy solution for Project Euler 14
I got the above down-voted, so here's some more detail.
Shekhar is right, you shouldn't be retesting the same condition, but it's actually non-material to your algorithm in this case. A cycle can only complete from the first condition, an even number, anyway. The blog post talks about this and other optimisations you can do to speed up the computation.
You need to make "num" a long, even with the revised non-repeated test algorithm or at various points in your cycle it will exceed the range of an int, and this'll then give you a wrong answer.
Also, you shouldn't call Solve() twice in the outer "i" loop either, store the result of the first call in a variable and just assign it if it's greater.
All that said, you don't need all that code. Less code means less stuff that can go wrong. Here's a simple implementation of a Solve() function that does the job.
public static int Solve(long num) {
int count = 1;
while (num > 1) {
num = (num & 1) == 0 ? num / 2 : 3 * num + 1;
count++;
}
return count;
}
(num & 1) masks off all the bits except the last, so it leaves 0 for an even number, and 1 for an odd number. It's just a shorthand way of doing your evenorodd() function.
The =?: syntax (if you've not seen it before - this is a ternery operator) does the test, then what to return if true, then what to return if false. Again, just a shorthand for an if-then-else where you need to do a single value assignment.
Hope this helps.

finding the largest digit in an integer using recursion

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;
}

Categories