Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
I found the The implements of Integer numberOfTrailingZeros method in java as follows
public static int numberOfTrailingZeros(int i) {
// HD, Figure 5-14
int y;
if (i == 0) return 32;
int n = 31;
y = i <<16; if (y != 0) { n = n -16; i = y; }
y = i << 8; if (y != 0) { n = n - 8; i = y; }
y = i << 4; if (y != 0) { n = n - 4; i = y; }
y = i << 2; if (y != 0) { n = n - 2; i = y; }
return n - ((i << 1) >>> 31);
}
It's take me a while to understand, here is my solution :
public static int numberOfTrailingZeros(int i) {
if (i == 0) return 32;
int num = 0;
while ((i & 1) == 0) {
i >>= 1;
num ++;
}
return num;
}
My question is what's the better solution? How can I come up with those implements such as in JDK Integer bitCount,highestOneBit,rotateLeft etc methods?
as I know the JDK's numberOfTrailingZeros use less + opeartor, and will be having higher performance when dealing with '0x70000000','0x60000000', and anything else?
What the java JDK is doing is sort of a binary search in the number to find the number of trailing zeros. It tries to shift the number left by powers of 2 to see if the shifted number becomes 0. If it doesn't, there are some set bits that are too far to the right, so the method keeps that shifted number, decrements the final count, and tries again with the next smallest power of 2.
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I got this Java function and I have to write the piece of code which results by unfolding the loop three times. What does it mean?
int f(int x, int y) {
while (true) {
int m = x % y;
if(m == 0) return y;
x = y;
y = m;
}
}
It means to repeat the code inside the loop a number of times, then refactoring the code to optimize it.
Let's see how it goes if we repeat once.
int f(int x, int y) {
while (true) {
int m = x % y;
if(m == 0) return y;
x = y;
y = m;
m = x % y;
if(m == 0) return y;
x = y;
y = m;
}
}
By rotating the use of the variables, we can eliminate the two simple assignments in the middle, thereby optimizing the code.
int f(int x, int y) {
while (true) {
int m = x % y;
if(m == 0) return y;
x = y % m;
if(x == 0) return m;
y = x;
x = m;
}
}
Now repeat it one more time, and rotate the variables in the third copy, for a total of 3 times the "same" code, as specified in the assignment.
I'll leave it to you to do that, since it is your assignment to complete. If done correctly, you'll find that there are no simple assignments in the result.
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 2 years ago.
Improve this question
I have the following binary search method and the following driver code. Both of the values I search for show in the output are present in the array.
Search Method
//Method for binary search. This method will also cut our array
public static int binarySearch(int[] nums, int x) {
//Bounds
int l = 0, r = nums.length - 1;
//While the size of the array is not 1
while (l <= r) {
//Middle element
int m = l + (r - 1) / 2;
//If our element is the middle
if (nums[m] == x) return m;
//If x is greater, cut to right half
else if (x > nums[m]) l = m + 1;
//Else, ignore right half
else r = m - 1;
}
//If we didn't find the element
return -1;
}
Driver code and output
public class searcher {
public static void main(String[] args) {
/* Initialize a new scanner for user input, initialize random for the
computer to pick a number */
Scanner s = new Scanner(System.in);
//Variable for user input
int guess;
//Do-while loop
do {
System.out.println("Enter a number to search for (0 to quit): ");
//Get the user's guess
guess = s.nextInt();
//Search for the guess in the array of numbers
int i = binarySearch(nums, guess);
System.out.println(i);
//If the number is not found
if (i == -1) {
System.out.println("Your number does not occur in this list.");
}
//If it is
else {
System.out.println("Your number occurs at position " + i);
}
} while (guess != 0);
}
}
/*
Output
Enter a number to search for (0 to quit):
1
1
Your number occurs at position 1
Enter a number to search for (0 to quit):
90
<------- Program doesn't stop running from here...? */
I'm expecting to get an output for the index of the number entered if its found, and if not, the method should return -1 so I can print not found
You are subtracting 1 twice.
r = nums.length - 1;
and then
int m = l + (r - 1) / 2;
should be
int m = l + (r - l) / 2;
int m = l + (r - 1) / 2; // this is not correct, you are subtracting "1"
you need to subtract "left" (variable names edited for clarity):
int mid = left + (right - left) / 2;
or, a bit better:
int mid = (left+ right) >>> 1;
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
I need to write a Javadoc comment for this method:
public static int maxDigit(int n)
{
if (n < 0) return maxDigit(-n);
if (n < 10) return n;
return n % 10 > maxDigit(n / 10) ? n % 10 : maxDigit(n / 10);
}
Basically, it returns the largest digit of a number. For instance, if n=36920 it will return 9. But I don't know how to write the inside's method documentation
i tried to write it but i don't know if it's correct could you help?
if (n < 0)
//in case of n<0 returns -n to the method in order to make the number positive
return maxDigit(-n);
// checks if the number is a digit
if (n < 10)
return n;
//calls the maxDigit method with n - one digit every time , until n<10
int max = maxDigit(n / 10);
// checks if the remainder of n/10 is bigger than max
return (n % 10 > max)? n % 10 : max;
}
/** Find the largest digit in decimal representation of given number.
*#param n The number to search in
*#return The largest digit
*/
public static int maxDigit(int n)
{
if (n < 0) return maxDigit(-n);
if (n < 10) return n;
int max_ = maxDigit(n / 10)
return n % 10 > max_ ? n % 10 : max_;
}
Is this what you meant?
By the way, I optimised the method for you a little. Now it won't cause tree-recursion.
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 7 years ago.
Improve this question
The code is supposed to cycle through all the numbers until it finds two numbers that can fulfill the conditions:
The factor of the number must consist of half of the original numbers digits
And the factor numbers must not be a multiple of 100. PS. the factor numbers are T and H.
However the code is not working
import java.util.Scanner;
public class VampierSlayer {
public static void main(String[] args) {
Scanner S = new Scanner(System.in);
System.out.println("Input A Even Digit Integer");
int i = S.nextInt();
String iS = Integer.toString(i);
int t = 0;
int h = 0;
for (h = 0; h < 1000000000; h++) {
if (h * t == i && iS.length() / 2 == Integer.toString(h).length()
&& iS.length() / 2 == Integer.toString(t).length() && h % 100 == 1 && t % 100 == 1) {
System.err.println("Finish");
break;
} else {
t++;
h = h - 1;
}
if (t > 1000) {
t = 0;
h = h + 1;
}
System.out.println(t + " " + h);
}
System.out.println(Integer.toString(h) + "," + t);
}
}
First, you're iterating through all numbers in a bit inconsistent way, you won't get all possible t-h combinations that way. Much better way would be to use 2 nested for-loops:
for (int h = 0; h < ...; h++) {
for (int t = 0; t < ...; t++) {
...
}
}
Next, you should do some research about how modulo works, you should have
h % 100 == 0 && t % 100 == 0
to properly check that numbers t and h are multiples of 100.
"And the factor numbers must not be a multiple of 100." Doesn't this mean:
if (h * t == i && iS.length() / 2 == Integer.toString(h).length()
&& iS.length() / 2 == Integer.toString(t).length()
&& h % 100 != 0 && t % 100 != 0)
Closed. This question is off-topic. It is not currently accepting answers.
Want to improve this question? Update the question so it's on-topic for Stack Overflow.
Closed 11 years ago.
Improve this question
I faced an interview. where I was asked the following question
Write a function in any of programming language that computes the nth power of a number w/o using + * or ^ or declaring a new variable inside the function or using any library function (eg Math lib in java).
I have used pow function of java Math.pow(a, b)
Thanks
They're asking whether you understand recursion. Considering x ^ k for some integer k,
when k < 0, xk = xk+1 / x
when k = 0, xk = 1
when k > 0, xk = xk-1 * x
Turning this into code shouldn't be too bad. Let's use multiplication for now, and take it out later.
double recursivePower(double x, int k) {
if (k < 0) {
return power(x, ++k) / x;
} else if (k == 0) {
return 1;
} else {
return power(x, --k) * x;
}
}
Now, to get rid of the multiplication. Since n * m = n / (1/m), we can rewrite the last calculation as power(x, --k) / (1/x):
double recursivePower(double x, int k) {
if (k < 0) {
return recursivePower(x, ++k) / x;
} else if (k == 0) {
return 1;
} else {
return recursivePower(x, --k) / (1 / x);
}
}
Fractional exponents could probably be done in the same style. If they want irrational exponents to be handled in the same way, I'd ask for Google and a fair amount of time to think about the problem.
static public int power(int value, int pow){
if(pow == 0) return 1;
return value * power(value, pow -1);
}
Done in JavaScript:
function power(num,pow){
if (pow == 0) return 1
num /= 1/(power(num,--pow))
return num
}
Call it like:
power(2,0) // -> 1
power(5,2) // -> 25
power(7,3) // -> 343
I feel like inverse division is cheating the no * operator rule, but eh, maybe that's what they were looking for.
I am using java programming language. The interviewer restricted you to declare a new variable inside the method better you pass it to the function. The interviewer didnt restrict you to use division operator (/) so you can use that.
static double getNthPowerOfNumber(double originalNumber,
int power) {
if (power == 0) {
return 1;
}
if (originalNumber == 0) {
return 0;
} else {
originalNumber/=1/getNthPowerOfNumber(originalNumber, --power);
return originalNumber;
}
}
if you want to get 5th power of a number 3 then write System.out.println("4..double..." + getNthPowerOfNumber(4, 1));