I have a class that generates a random number within a given interval.
public class Dice{
//code.....
public int throwDice(){
Random randomGen = new Random();
int min = 1;
int max = sides; //sides gets a value earlier in the class
int randomNum = randomGen.nextInt((max - min) + 1) + min;
return randomNum;
}
Then the assignment says that I'm going to use a boolean method that looks like this (with my already written code in it as well):
private boolean step(){
int res = this.dice.throwDice();
int startpos = this.bridge.getFirst();
if (res == 10){ //this works
return false;
}
else if (res => 7 && res <= 9 ){ //but the error occurs here
//code....
return true;
}
What I need to do is check if the generated random number in the throwDice() method is within a certain interval of numbers.
The problem is that I get an error that says that I can't convert an int to a boolean. Is there a way to get around this? Or do I have to rethink my whole solution?
=> should be the other way around.
else if (res => 7 && res <= 9 ){
should be
else if (res >= 7 && res <= 9 ){
Equality and Relational Operators
== Equal to
!= Not equal to
> Greater than
>= Greater than or equal to <-----
< Less than
<= Less than or equal to
Source Equality and Relational Operator
Related
I wrote a simple program to calculate the maximum number of times square root can be calculated on a number , input is an interval from num1 to num2
eg:
if the input is (1,20), answer is 2, since square root of 16 is 4 , and square root of 4 is 2 .
int max = 0;
for (int i = num1; i <= num2; i++) {
boolean loop = true;
int count = 0;
int current = i;
if (i == 1) {
count++;
} else {
while (loop) {
double squareRoot = Math.sqrt(current);
if (isCurrentNumberPerfectSquare(squareRoot)) {
count++;
current = (int) squareRoot;
} else {
loop = false;
}
}
}
if (count > max) {
max = count;
}
}
return max;
static boolean isCurrentNumberPerfectSquare(double number) {
return ((number - floor(number)) == 0);
}
I get the answer, but was wondering wether this can be improved using some mathematical way ?
Any suggestions ?
To avoid more confusion here my final answer to this topic.
A combination of both previously mentioned approaches.
What 'Parameswar' is looking for is the largest perfect square formed by the lowest base.
Step 1 -
To get that calculate the largest possible perfect square based on your num2 value.
If it is outside your range, you have no perfect square within.
Step 2 -
If it is within your range, you have to check all perfect square formed by a lower base value with a higher number of times.
Step 3 -
If you find one that is within your range, replace your result with the new result and proceed to check lower values. (go back to Step 2)
Step 4 -
Once the value you check is <= 2 you have already found the answer.
Here some sample implementation:
static class Result {
int base;
int times;
}
static boolean isCurrentNumberPerfectSquare(double number) {
return ((number - Math.floor(number)) == 0);
}
private static int perfectSquare(int base, int times) {
int value = base;
for (int i = times; i > 0; i--) {
value = (int) Math.pow(base, 2);
}
return value;
}
private static Result calculatePerfectSquare(int perfectSquare) {
Result result = new Result();
result.base = (int) Math.sqrt(perfectSquare);
result.times = 1;
while (result.base > 2 && isCurrentNumberPerfectSquare(Math.sqrt(result.base))) {
result.base = (int) Math.sqrt(result.base);
result.times += 1;
}
System.out.println(perfectSquare + " -> " + result.base + " ^ " + result.times);
return result;
}
static int maxPerfectSquares(int num1, int num2) {
int largestPerfectSqr = (int) Math.pow(Math.floor(Math.sqrt(num2)), 2);
if (largestPerfectSqr < num1) {
return 0;
}
Result result = calculatePerfectSquare(largestPerfectSqr);
int currentValue = result.base;
while (currentValue > 2) {
// check lower based values
currentValue--;
int newValue = perfectSquare(currentValue, result.times + 1);
if (newValue >= num1 && newValue < num2) {
result = calculatePerfectSquare(newValue);
currentValue = result.base;
}
}
return result.times;
}
Edit - My assumption is incorrect. Refer to the answer provided by "second".
You can remove the outer loop, num2 can be directly used to determine the number with the maximum number of recursive square roots.
requiredNumber = square(floor(sqrt(num2)));
You just need to check to see if the requiredNumber exists in the range [num1, num2] after finding it.
So the refactoring code would look something like this,
int requiredNumber = Math.pow(floor(Math.sqrt(num2)),2);
int numberOfTimes=0;
if(requiredNumber>=num1) {
if (requiredNumber == 1) {
numberOfTimes=1;
} else{
while (isCurrentNumberPerfectSquare(requiredNumber)) {
numberOfTimes++;
}
}
}
Edit 4: for a more optimal approach check my other answer.
I just leave this here if anybody wants to try to follow my thought process ;)
Edit 3:
Using prime numbers is wrong, use lowest non perfect square instead
Example [35,37]
Edit 2:
Now that I think about it there is a even better approach, especially if you assume that num1 and num2 cover a larger range.
Start with the lowest prime number 'non perfect square' and
calculate the maximum perfect square that fits into your range.
If you have found one, you are done.
If not continue with the next prime number 'non perfect square'.
As a example that works well enough for smaller ranges:
I think you can improve the outerloop. There is no need to test every number.
If you know the smallest perfect square, you can just proceed to the next perfect square in the sequence.
For example:
[16, 26]
16 -> 4 -> 2 ==> 2 perfect squares
No neeed to test 17 to 24
25 -> 5 ==> 1 perfect square
and so on ...
#Chrisvin Jem
Your assumption is not correct, see example above
Edit:
Added some code
static int countPerfectSquares(int current) {
int count = 0;
while (true) {
double squareRoot = Math.sqrt(current);
if (isCurrentNumberPerfectSquare(squareRoot)) {
count++;
current = (int) squareRoot;
} else {
return count;
}
}
}
static boolean isCurrentNumberPerfectSquare(double number) {
return ((number - Math.floor(number)) == 0);
}
static int numPerfectSquares(int num1, int num2) {
int max = 0;
if (num1 == 1) {
max = 1;
}
int sqr = Math.max(2, (int) Math.floor(Math.sqrt(num1)));
int current = (int) Math.pow(sqr, 2);
if (current < num1) {
current = (int) Math.pow(++sqr, 2);
}
while (current <= num2) {
max = Math.max(countPerfectSquares(current), max);
current = (int) Math.pow(++sqr, 2);
}
return max;
}
I write down a code which find out quotient after dividing two number but without using multiplication,division or mod operator.
My code
public int divide(int dividend, int divisor) {
int diff=0,count=0;
int fun_dividend=dividend;
int fun_divisor=divisor;
int abs_dividend=abs(dividend);
int abs_divisor=abs(divisor);
while(abs_dividend>=abs_divisor){
diff=abs_dividend-abs_divisor;
abs_dividend=diff;
count++;
}
if(fun_dividend<0 && fun_divisor<0){
return count;
}
else if(fun_divisor<0||fun_dividend<0) {
return (-count);
}
return count;
}
My code passes the test cases like dividend=-1, divisor=1 or dividend=1 and divisor=-1. But it cannot pass the test case like dividend = --2147483648 and divisor =-1. However I have a if statement when both inputs are negative.
if(fun_dividend<0 && fun_divisor<0){
return count;
}
When my inputs are -2147483648 and -1 it returned zero. I debugged my code and find out that it cannot reach the the inner statements of while loop. It just check the while loop and terminated and execute
if(fun_dividend<0 && fun_divisor<0){
return count;
}
It is very obvious, both inputs are negative, so I was using Math.abs function to make them positive. But when I try to see the values of variables abs_dividend and abs_divisor they show me negative values.
Integer max can take a 9 digit number. So how could I pass this test case? As per this test case dividend is a 10 digit number which is not valid for a integer range.
As per the test case the output that I get should be 2147483647.
How could I solve the bug?
Thank you in advance.
Try using the bit manipulation for this as follows:
public static int divideUsingBits(int dividend, int divisor) {
// handle special cases
if (divisor == 0)
return Integer.MAX_VALUE;
if (divisor == -1 && dividend == Integer.MIN_VALUE)
return Integer.MAX_VALUE;
// get positive values
long pDividend = Math.abs((long) dividend);
long pDivisor = Math.abs((long) divisor);
int result = 0;
while (pDividend >= pDivisor) {
// calculate number of left shifts
int numShift = 0;
while (pDividend >= (pDivisor << numShift)) {
numShift++;
}
// dividend minus the largest shifted divisor
result += 1 << (numShift - 1);
pDividend -= (pDivisor << (numShift - 1));
}
if ((dividend > 0 && divisor > 0) || (dividend < 0 && divisor < 0)) {
return result;
} else {
return -result;
}
}
I solve it this way. Give preference to data type long over int wherever there is a chance of overflow upon left-shift. Handle the edge case at the very beginning to avoid the input values getting modified in the process. This algorithm is based upon the division technique we used to make use in school.
public int divide(int AA, int BB) {
// Edge case first.
if (BB == -1 && AA == Integer.MIN_VALUE){
return Integer.MAX_VALUE; // Very Special case, since 2^31 is not inside range while -2^31 is within range.
}
long B = BB;
long A = AA;
int sign = -1;
if ((A<0 && B<0) || (A>0 && B>0)){
sign = 1;
}
if (A < 0) A = A * -1;
if (B < 0) B = B * -1;
int ans = 0;
long currPos = 1; // necessary to be long. Long is better for left shifting.
while (A >= B){
B <<= 1; currPos <<= 1;
}
B >>= 1; currPos >>= 1;
while (currPos != 0){
if (A >= B){
A -= B;
ans |= currPos;
}
B >>= 1; currPos >>= 1;
}
return ans*sign;
}
Ran with the debugger and found that abs_dividend was -2147483648.
Then the comparison in while (abs_dividend >= abs_divisor) { is false and count is never incremented.
Turns out the explanation is in the Javadoc for Math.abs(int a):
Note that if the argument is equal to the value of Integer.MIN_VALUE, the most negative representable int value, the result is that same value, which is negative.
Presumably, this is because Integer.MAX_VALUE is 2147483647, so there is no way of representing positive 2147483648 with an int. (note: 2147483648 would be Integer.MAX_VALUE + 1 == Integer.MIN_VALUE)
I'm totally new to Java and I'm implementing a simple function to convert string to integer on Leetcode.
public int myAtoi(String str) {
if(str.length() == 0){
return 0;
}
str = str.trim();
int n = str.length();
int signal = 0;
if(n == 1 && str.equals("+") || str.equals("-")){
return 0;
}
if(str.charAt(0) == '+'){
signal = 1;
}else if(str.charAt(0) == '-'){
signal = -1;
}
int i = (signal != 0)? 1 : 0;
if(signal == 0){
signal = 1;//default
}
int res = 0;
while(i < n){
char c = str.charAt(i);
if(!Character.isDigit(c)){
return res * signal;
}
//res = res * 10 + c - '0';
if(signal * res > Integer.MAX_VALUE){
return Integer.MAX_VALUE;
}
if(signal * res < Integer.MIN_VALUE){
return Integer.MIN_VALUE;
}
res = res * 10 + c - '0';
++i;
}
return res * signal;
}
I know java integer has the MAX_VALUE of 2147483647. When my input is 2147483648 the output should be 2147483647 but indeed it's -214748648. I really have no idea what's wrong in here. Can anybody help me to understand this?
Consider this example
public static void main(String args[]) {
int i=2147483647;
System.out.println("i="+i);
int j=++i;
System.out.println("Now i is="+i);
System.out.println("j="+j);
}
What happens?
output will be :
i = 2147483647
Now i is=-2147483648
j=-2147483648
The maximum value of integer is 2,147,483,647 and the minimum value is -2,147,483,648. Here in j (with post increment of i), we have crossed the maximum limit of an integer
This is exactly what is happening in your case too .
Because the integer overflows. When it overflows, the next value is Integer.MIN_VALUE
Why?
Integer values are represented in binary form, and there is binary addition in java. It uses a representation called two's complement, in which the first bit of the number represents its sign. Whenever you add 1 to the largest Integer(MAX INT), which has a bit sign of 0, then its bit sign becomes 1 and the number becomes negative.
So, don't put > MAX INT as input, else put a condition in your code to check it on input itself.
The input is never +2147483648 since that value can't be represented as a Java int.
It will wrap around to the negative number you observe, so accounting for that result.
For my Java class, we have to write a program that displays all palindromic primes based on a number the user inputs. There are a couple other questions like this, but I need to do it without creating an array, or just typing in all of the palindromic primes.
My program works, and displays all primes, but the problem is that it displays ALL primes, not just the palindromic ones. I don't know where the error is, but I would appreciate any help I can get!
Thanks,
Ben
import java.util.Scanner;
public class PalindromePrimes {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int startingPoint = 1;
int startingPrime = 2;
final int printPerLine = 10;
IsItPrime(startingPrime);
IsItPalin(startingPrime);
System.out.println("Please Enter a Number: ");
int n = in.nextInt();
while (startingPoint <= n)
{
if (IsItPrime(startingPrime) && IsItPalin(startingPrime)) {
System.out.print(startingPrime + " ");
if (startingPoint % printPerLine == 0)
System.out.println();
startingPoint++;
}
startingPrime++;
}
}
public static boolean IsItPrime(int sPrime) {
if (sPrime == 2) {
return true;
}
for(int i = 2; 2 * i < sPrime; i++) {
if(sPrime % i == 0){
return false;
}
}
return true;
}
public static boolean IsItPalin(int sPrime) {
int p;
int reverse = 0;
while (sPrime > 0) {
p = sPrime % 10;
reverse = reverse * 10 + p;
sPrime = sPrime / 10;
}
if (sPrime == reverse) {
return false;
}
return true;
}
}
You could really improve both functions:
Some notes about IsItPrime:
Check first only for even numbers (you are doing this)
The for-loop could begin in 3 and increment by 2, to check only odd numbers, the even are checked in the previous point.
The for-loop only needs to check from 3 .. sqrt(N) + 1, if the number is not prime. It would be a prime if the number is less or equal to sqrt(N) and devides N.
Function IsItPrime improve:
public static boolean IsItPrime(int sPrime) {
if (sPrime % 2 == 0 && sPrime != 2) {
return false;
}
int sqrtPrime = (int)Math.sqrt(sPrime);
for (int i = 3; i <= sqrtPrime; i += 2) {
if (sPrime % i == 0) {
return false;
}
}
return true;
}
Some notes about IsItPalin:
The return result is swapped, when sPrime == reverse is palindrome, you must return true, not false.
The other problem is that in the function you are modifying the parameter sPrime in the while-loop, you need to save the original value for comparing in sPrime == reverse.
Function IsItPalin improved:
public static boolean IsItPalin(int sPrime) {
int sPrimeBackup = sPrime;
int reverse = 0;
while (sPrime > 0) {
reverse = reverse * 10 + sPrime % 10;
sPrime = sPrime / 10;
}
return (sPrimeBackup == reverse);
}
The problem is in the IsItPalin method. You are changing the value of sPrime, but then comparing sPrime to reverse. Make a copy of sPrime and compare the copy to reverse. Also, you should return true if they are equal, not false.
It looks like the problem is with your IsItPalin method. It's almost right, except for two problems.
The first problem is this:
if (sPrime == reverse) {
return false;
}
return true;
Whenever your prime number is equal to the reverse, you're returning false! This is the opposite of what we want.
The fix is to switch "true" and "false":
if (sPrime == reverse) {
return true;
}
return false;
We can actually simplify this into a single line:
return sPrime == reverse;
The second problem is with sPrime. Within your while loop, you're decreasing sPrime, and will only exit the loop when sPrime is equal to zero. That means that the only time sPrime will be equal to reverse is when you input the value of 0. To fix this, make a copy of sPrime at the top of the method and compare the copy to reverse.
The fixed version would look like this:
public static boolean IsItPalin(int sPrime) {
int copy = sPrime;
int reverse = 0;
while (sPrime > 0) {
int p = sPrime % 10;
reverse = reverse * 10 + p;
sPrime = sPrime / 10;
}
return copy == reverse;
}
This solution doesn't involve a loop, so it's probably faster
public static boolean isPaladrome(int mNumber) {
String numToString = String.valueOf(mNumber);
int sLength = numToString.length();
int midPoint = sLength / 2;
return (new StringBuilder(numToString.substring(0, midPoint)).reverse()
.toString()).equals(numToString.substring(sLength - midPoint));
}
I am trying to find a way to reverse a number without
Converting it to a string to find the length
Reversing the string and parsing it back
Running a separate loop to compute the Length
i am currently doing it this way
public static int getReverse(int num){
int revnum =0;
for( int i = Integer.toString(num).length() - 1 ; num>0 ; i-- ){
revnum += num % 10 * Math.pow( 10 , i );
num /= 10;
}
return revnum;
}
But I would Like to implement the above 3 conditions.
I am looking for a way , possibly using the bit wise shift operators or some other kind of bitwise operation.
Is it possible ? If so how ?
PS : If 1234 is given as input it should return 4321. I will only be reversing Integers and Longs
How about:
int revnum = 0;
while (num != 0) {
revnum = revnum * 10 + (num % 10);
num /= 10;
}
return revnum;
The code expects a non-negative input.
This may or may not matter to you, but it's worth noting that getReverse(getReverse(x)) does not necessarily equal x as it won't preserve trailing zeroes.
How about this? It handles negative numbers as well.
public int getReverse(int num){
int rst=0;
int sign;
sign=num>0?1:-1;
num*=sign;
while(num>0){
int lastNum = num%10;
rst=rst*10+lastNum
num=num/10;
}
return rst*sign;
}
Integer.MAX_VALUE or Integer.MIN_VALUE is not at all considered in any of the solutions.
For eg: if the input is -2147483647 or 2147483647 the o/p will be 1126087180 and -1126087180 respectively.
Please try the below solutions where both the conditions are handled, so if at any point of time the number is going beyond the boundary conditions i.e., INPUT_VALUE > Integer.MAX_VALUE or INPUT_VALUE < Integer.MIN_VALUE it would return 0
class ReversingIntegerNumber {
public int reverse(int originalNum) {
boolean originalIsNegative = originalNum > 0 ? false : true;
int reverseNum = 0;
int modValue;
originalNum = Math.abs(originalNum);
while(originalNum != 0) {
modValue = originalNum % 10;
if(reverseNum > (Integer.MAX_VALUE - modValue)/10) {
return 0;
}
reverseNum = (reverseNum * 10) + modValue;
originalNum /= 10;
}
return originalIsNegative ? -1 * reverseNum : reverseNum;
}
}