Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I have two methods, that I believe can be made better way, but can't find this way.
First:
public int calcPow(long num) {
int count = 0;
while(num/2!=0) {
num = num/2;
count++;
}
return count;
}
The second is:
private long findParentNumber(long value) {
for(int bitNum = 0; bitNum < Long.SIZE; bitNum++) {
if((value & (1L << bitNum)) != 0) {
return value ^ (1L << bitNum);
}
}
throw new RuntimeException("No parent number found");
}
I believe, there are ways to do the same without loops. Can you help?
Cheers!
For the second one, you're unsetting the lowest set bit. There's a relatively well known bithack to do that, though only relatively because it seems that bithacks in general are not well known.
Anyway, it's
return x & (x - 1);
The logic here is that in x - 1, there's a borrow running through the lowest zeroes until it hits the lowest 1-bit, which it unsets. The lowest zeroes are left set, they are then removed by ANDing it with the original number.
You can write the first one in terms of numberOfLeadingZeros, which would be more obviously correct than floating point hacks which always make you think about how accurate they might be (and in any case they're slow, you might be better off with the loop).
Edit: for completeness, that would be 63 - numberOfLeadingZeros(x), it differs from your definition at x = 0 but that's a bad input anyway.
Try this for the first one.
public int calcPow(long num) {
if (num == 0) return 0;
if (num < 0) num = -num;
return Long.numberOfTrailingZeros(Long.highestOneBit(num));
}
Or this suggested by harold
public int calcPow(long num) {
return num == 0 ? 0
: 63 - Long.numberOfLeadingZeros(Math.abs(num));
}
For the first one, you can use the Math.log method that already exists:
public static int log2(long number) {
return (int) Math.floor(Math.log(number) / Math.log(2));
}
or this faster function suggested by saka1029:
public static int log2(long number) {
return number == 0? 0: Long.numberOfTrailingZeros(Long.highestOneBit((number < 0)? number * -1: number));
}
As you can see I also changed the method to static, since I see no point in having to use an Object to get a log when no object is involved. And secondly I changed the names into something more fitting.
For the second one you can use the bit-wise check operator &:
public static long removeSmallBit(long value) {
return value & (value - 1);
}
Essentially you are removing the smallest bit from the variable, and return that number after you change that bit to 0. And as you can see again I made the method static and changed the name. 2nd answered inspired by this answer submitted by harold
Related
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
Trying to find out if any of the digits in a number are odd, if so return true. If any are even then return false. Getting error: incompatible types: boolean cannot be converted to int. Any help is appreciated.
public class allDigitsOddTest{
public static void main(String[] args) {
allDigitsOdd(756410);
}
public static int allDigitsOdd(int num){
boolean value = true;
int evens = 0;
int odds = 0;
while (num > 0){
int remainder = num % 10;
if (remainder % 2 == 0){
evens++;
}
else{
odds++;
}
num = num / 10;
}
if (evens > 0){
value = false;
}
return value;
}
}
Your return type is int, instead of boolean
change
public static int allDigitsOdd(int num)
to
public static boolean allDigitsOdd(int num) {
In the beginning it helped me a lot to look at Methods like this:
You try to unlock your door at home, which you have the keys for. It doesn't matter which of your three keys you use, because it works with every one of your keys. But if you try your car key it won't fit and the mission is a failure.
So look at the different data types as keys, you can lock the door with your main key, and your girlfriend unlocks it later with hers.
-> One key in, another one of the same out if you understand what I mean.
Same for Java, you give an integer into the method, you can return every integer you want, but not a different data type (or key type).
Maybe an odd example, but for some reason it helped me a lot.
there are many questions about how to convert recursive to non-recursive, and I also can convert some recursive programs to non-recursive form
note: I use an generalized way (user defined Stack), because I think it is easy to understand, and I use Java, so can not use GOTO keyword.
Things don't always go so well, when I meet the Backtracking, I am stuck. for example, The subset problem. and my code is here: recursive call with loop
when i use user defined Stack to turn it to non-recursive form. I do not know how to deal with the loop (in the loop existing recursive call).
I googled found that there is many methods such as CPS. and I know there is an iterative template of subset problem. but i only want to use user defined Stack to solve.
Can someone provide some clues to turn this kind of recursive(recursive with loop) to non-recursive form(by using user defined Stack, not CPS etc..) ?
here is my code recursive to non-recusive(Inorder-Traversal), because of there is no loop with recursive call, so i can easily do it. also when recursive program with a return value, I can use a reference and pass it to the function as a param. from the code, I use the Stack to simulated the recursive call, and use "state" variable to the next call point(because java does not allow using GOTO).
The following is the information I have collected. It seems that all of them does not satisfy the question I mentioned(some use goto that java not allowed, some is very simple recursive means that no nested recursive call or recursive call with loop ).
1 Old Dominion University
2 codeproject
----------------------------------Split Line--------------------------------------
Thks u all. after when I post the question... It took me all night to figure it out. here is my solution: non-recursive subset problem solution, and the comment of the code is my idea.
To sum up. what i stuck before is how to deal with the foo-loop, actually, we can just simply ignore it. because we are using loop+stack, we can do a simple judgment on whether to meet the conditions.
On your stack, have you thought about pushing i (the iteration variable)?
By doing this, when you pop this value, you know at which iteration of the loop you were before you pushed on the stack and therefore, you can iterate to the next i and continue your algorithm.
Non-negative numbers only for simplicity. (Also no IntFunction.)
The power function, as defined here, is a very simple case.
int power(int x, int exponent) {
if (exponent == 0) {
return 1;
} else if (exponent % 2 == 0) {
int y = power(x, exponent /2);
return y * y;
} else {
return x * power(x, exponent - 1);
}
}
Now the stack is there to do in the reverse order to a partial result, what you did in recursion with the result.
int power(final int x, int exponent) {
Stack<Function<Integer, Integer>> opStack = new Stack<>();
final Function<Integer, Integer> square = n -> n * n;
final Function<Integer, Integer> multiply = n -> x * n;
while (exponent > 0) {
if (exponent % 2 == 0) {
exponent /= 2;
opStack.push(square);
} else {
--exponent;
opStack.push(multiply);
}
}
int result = 1;
while (!opStack.isEmpty()) {
result = opStack.pop().apply(result);
}
return result;
}
An alternative would be to "encode" the two branches of if-else (odd/even exponent) by a boolean:
int power(final int x, int exponent) {
BooleanStack stack = new BooleanStack<>();
while (exponent > 0) {
boolean even = exponent % 2 == 0;
stack.push(even);
if (even) {
exponent /= 2;
} else {
--exponent;
}
}
int result = 1;
while (!stack.isEmpty()) {
result *= stack.pop() ? result : x;
}
return result;
}
So one has to distinghuish:
what one does to prepare the recursive arguments
what one does with the partial results of the recursive calls
how one can merge/handle several recursive calls in the function
exploit nice things, like x being a final constant
Not difficult, puzzling maybe, so have fun.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I have a task to write a simple Java program:
I have two integers a and b. If a>10 and b<10 then it should print out "balanced" and if not then print out "unbalanced"
I know how to make this with 1 variable, but i don't have clue how to make it with 2.
Here is something I have tried:
public static void main(String args[]) {
int a = 1;
int b = 15;
if (a > 10 && b <= 10)
{
System.out.println("balanced");
}
else
{
System.out.println("unbalanced);
}
}
Your code not even compile since there is syntax error. You can make your mistake correct as follows.
int a = 1;
int b = 15;
if (a > 10 & b <= 10) { // why <= by reading your question it should <
System.out.println("balanced");
} else {
System.out.println("unbalanced");
}
Now out put is unbalanced.
Now let's review your code. you have use &(non short circuit) and here. That's not good since always non short circuit operands evaluate both side of the expression.
So you should use && (short circuit)
int a = 1;
int b = 15;
if (a > 10 && b <= 10) {
System.out.println("balanced");
} else {
System.out.println("unbalanced");
}
What's wrong with non short circuit?
Consider following logic.
if(name!=null&name.getFirstName()=="same"){ // Now both side evaluate
}
what happen name==null?, name.getFirstName() will give you NullPointerException. If you use && short circuit you are same from this NPE
if(name!=null&&name.getFirstName()=="same"){ // if first case false not
evaluate second
}
Use && instead of & so that it does a logical and not a bitwise one.
You will find it clearer to read if you put brackets around (a > 10) && (b <= 10) as well.
I can't seem to figure this one out. I need to count how many numbers below a given number in which it is divisible.
Here is what I've tried:
public int testing(int x) {
if (x == 0) {
System.out.println("zero");
return x;
}
else if ((x % (x-1)) == 0) {
System.out.println("does this work?");
x--;
}
return testing(x-1);
}
That doesn't work and I don't know where to go from here. Anyone know what to do?
This is what is wrong:
public int testing(int x) {
If you want to make it recursive, you need to pass both the number to test and the number that you are currently checking. The first one will not change through the recursion, the second one will decrement. You cannot do what you express with only one parameter (unless you use a global variable).
This is not a task that should be solved with recursion.
If you MUST use recursion, the simplest way to do it is to have a second parameter, which is essentially an "I have checked until this number". Then you can increase/decrease this (depending on if you start at 0 or the initial number) and call the recursive on that.
Thing is, Java isn't a functional language, so doing all this is actually kind of dumb, so whoever gave you this exercise probably needs a bop on the head.
Your problem is that your expression x % (x - 1) is using the "current" value of x, which decrements on every call to the recursive function. Your condition will be false all the way down to 2 % (2 - 1).
Using a for loop is a much better way to handle this task (and look at the Sieve of Eratosthenes), but if you really have to use recursion (for homework), you'll need to pass in the original value being factored as well as the current value being tried.
You have a problem with your algorithm. Notice the recursion only ends when x == 0, meaning that your function will always return 0 (if it returns at all).
In addition, your algorithm doesn't seem to make any sense. You are basically trying to find all factors of a number, but there's only one parameter, x.
Try to make meaningful names for your variables and the logic will be easier to read/follow.
public int countFactors(int number, int factorToTest, int numFactors)
{
if (factorToTest == 0) // now you are done
return numFactors;
else
// check if factorToTest is a factor of number
// adjust the values appropriately and recurse
}
There is no need to use recursion here. Here's a non-recursive solution:
public int testing(int n) {
int count = 0;
for (int i = 1; i < n; i++)
if (n % i == 0)
count++;
return count;
}
BTW, you should probably call this something other than testing.
Using recursion:
private static int getFactorCount(int num) {
return getFactorCount(num, num - 1);
}
private static int getFactorCount(int num, int factor) {
return factor == 0 ? 0 : (num % factor == 0 ? 1 : 0)
+ getFactorCount(num, factor - 1);
}
public static void main(String[] args) {
System.out.println(getFactorCount(20)); // gives 5
System.out.println(getFactorCount(30)); // gives 7
}
This question already has an answer here:
Closed 10 years ago.
Possible Duplicate:
Horner's recursive algorithm for fractional part - Java
I am writing a program for Horne'r Algorithm, and I will be honest, I do not have much experience with recursion. I have this method set up to accept a fraction only (there is another method which accepts and returns the whole number) and it will return the result converted from base 'r' to base 10. I am unsure why, but the method does not seem to be going through the final iteration. Any suggestions as to what I need to do to correct this problem would be greatly appreciated.
(ex: c = 011, xFinal = 2, i = 2)
Expected answer = .375
Actual answer returned = .75
public static double getHornerFraction(long[] c, int xFinal, int i) {
if (i == 0) {
return ((double)c[i])/xFinal;
}
return (getHornerFraction(c, xFinal, i-1) + c[i])/xFinal;
}
From looking at what you specified and what you expect, I think the problem is that you are walking the array c in the wrong direction or otherwise specifying it incorrectly. I think that what you want to do is actually walk the array from index 0 to c.length.
public static double getHornerFraction(long[] c, int xFinal, int i) {
if (i == c.length) {
return 0;
}
return (getHornerFraction(c, xFinal, i+1) + c[i])/xFinal;
}
Call the above function with c = {0,1,1}, xFinal = 2, i = 0 and it should give what you expect.