Comparing Even/Odd numbers w/ java and boolean [closed] - java

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 5 years ago.
Improve this question
I am writing a method that takes in two numbers and will return true if they are both even or both odd... and will return false if only one is odd and one is even.
It needs to return a boolean statement, but it is not working.. Any help is appreciated! Thanks...
public static boolean compareEvenOdd(int x, int y) {
if((x % 2 ==0) && ( y% 2==0))||((x%2 != 0) && (y%2 != 0)){
return true;
} else
return false;
}

You can do the following (possibly the shortest version):
public static boolean compareEvenOdd(int x, int y) {
return ((x + y) % 2) == 0;
}
The sum of two odd numbers and the sum of two even numbers is even, the sum of one odd and one even number is odd. So you add the numbers and check if the solution is dividable by 2.

This is a really good opportunity to use a bitwise operator. You can use the binary AND (&) operator with the number 1 to reduce an integer to just its last binary digit. This last digit is always 0 for an even number and 1 for an odd number. If your two numbers have the same last binary digit, then they have the same parity - that is, they're both even or both odd. So I would write the method like this.
public boolean sameParity(int x, int y) {
return (x & 1) == (y & 1);
}
Note that the parentheses are important, because the usual Java order of operations puts == above &.

Seems you are missing an additional pair of parentheses around the condition in the if-statement.
This works for me:
public static boolean compareEvenOdd(int x, int y) {
if (((x % 2 ==0) && ( y% 2==0))||((x%2 != 0) && (y%2 != 0))){
return true;
} else
return false;
}
if this is not to your liking, yould you further specify what is not working? Is it throwing errors as you run it, is the output wrong,...?

Explication :
x and y are odd : x+y are even
x and y are even : x+y are even
x is odd and y is odd : x+y are odd
x is even and x is even : x+y are odd
public static boolean compareEvenOdd(int x, int y) {
return (x+y)%2==0
}

An if-statement always has the form if (...) with its own parentheses around the condition. Hence you missing just that.
So (with unneeded braces removed):
public static boolean compareEvenOdd(int x, int y) {
if ((x % 2 == 0 && y % 2 == 0)
|| (x%2 != 0 && y % 2 != 0)) {
return true;
} else
return false;
}
And as shown in the other answers this should be simplified,
as if+return boolean means using boolean redundantly, not to the fullest (like == true):
return (x % 2 == 0 && y % 2 == 0)
|| (x % 2 != 0 && y % 2 != 0);
return (x % 2) == (y % 2);
return (x - y) % 2 == 0;

Related

I was trying to solve a Leetcode problem, regarding identifying if the number entered is a palindrome or not

I understood the logic behind the problem's solution, but in the coded solution I am a bit confused about the return statement in the end. Please explain to me what is its significance, why is it being used, etc ? (not why return is used but why is that value being returned).
class Solution {
public boolean isPalindrome(int x) {
// 2 cases x < 0 = false case
// x > 0 = test case
if (x < 0 || x % 10 == 0 && x != 0){
return false;
}
else {
int newNum = 0;
while (x > newNum){
int r = (x % 10);
newNum = newNum * 10 + r;
x /= 10;
}
//the part I am confused about - below
return x == newNum || x == newNum / 10;
}
}
}
So to understand the Logic for the return statement let us take 2 numbers
1234321
678876
So one thing here While loop is doing is to create a new number(newNum) out of X and making sure that newNum stores the reverse of X till the middle point.
So in case of 1234321 , this while loop will execute till X=123 and newNum=1234.
After exiting out from while loop with these values, out of the 2 statements in return, x == newNum / 10 will give true result hence return statement will return true.which means the number is palindrome.
Please note here that the no. digits in given integer is odd(7)
Let us now Take other example 678876
In this case when the while loop ends, the value for the X would be 678 and newNum would be 678
out of the 2 statements in return, x == newNum this time will give true result hence return statement will return true again .which means the number is palindrome.
Please note here that the no. digits in given integer is even(6)
All in all, this statement return x == newNum || x == newNum / 10;
is to make sure that we are covering the condition for both Odd and even no. of digits in the given integer X.

How do I calculate this code's time complexity? [duplicate]

This question already has answers here:
Big O, how do you calculate/approximate it?
(24 answers)
Closed 3 years ago.
I'm struggling with calculating time complexity in this code.
Only capable of simple code at the moment...
just want to try with complex one!
public static int PATHWAY = 0;
public static int WALL = 1;
public static int MARKED = 2;
public static boolean find(int x, int y) {
if(x == 7 && y == 7) return true;
maze[x][y] = MARKED;
if(x != 0 && maze[x-1][y] == PATHWAY && find(x-1, y)) return true;
if(y != 0 && maze[x][y-1] == PATHWAY && find(x, y-1)) return true;
if(x != 7 && maze[x+1][y] == PATHWAY && find(x+1, y)) return true;
if(y != 7 && maze[x][y+1] == PATHWAY && find(x, y+1)) return true;
return false;
}
Well, in each recursive call you visit a single cell in your 2D array.
Since you mark the visited cells, you can't visit the same cell twice.
Hence the total recursive calls is bound by the length of the 2D array.
Apart from the recursive call, you perform a constant amount of work in each execution of the find() method.
Therefore the time complexity is O(N*M) if N is the number of rows and M the number of columns of the 2D array.
Of course, based on your stopping condition of if(x == 7 && y == 7) return true;, it looks like the dimensions of your 2D array are 8x8, which can be seen as a constant. That would make the running time O(1).
O(N*M) is the complexity for a general input array.
Basically you can calculate assignments and operations.
Have a
int assignments = 0;
int operations = 0;
which you will increment every time you do one.
Other way in doing this is to monitor the time, but it's not the most reliable one.
You can also calculate/approximate Big-O, check Big O, how do you calculate/approximate it?
Well it's not that hard, it actually uses DFS in order to find a path. the order of DFS is O(V+E), where V is the number of vertices and E is the number of edges.
In this case you are using a adjacency matrix to represent your graph. so in worst case the time complexity would be O(M*N), where M is the number of rows and N is the number of columns.

How do I check divisibility in Java?

I am trying to check if on number is divisible by another, and currently I use this method:
int x = 70;
int y = 30;
if(x/y == Math.round(x/y)) {
...
}
Is there a simpler way?
You can use modulus operator like this in your condition,
if (x%y == 0)
A good way is to use modulus operator, which returns the remainder after dividing by a number, e.g.
5 % 2 = 1 (1 is the remainder after 5 is divided by 2)
So for a number to be divisible by another, it should have a remainder of 0 (i.e. x % y = 0)
if (x % y == 0)
{
//x is divisible by y
}
else
{
//x is not divisible by y
}

How to write a LessThan method without using the operator

How would you recursively write a method that checks if a number is less than the other without using the '<' operator?
You can only use the plus, minus, times, and equals operators.
It must be recursive
x and y will always be 0 or greater
Should return boolean
If needed, you can make other methods but they must follow rules above.
Cove I've got so far:
public static boolean isLessThan(int x, int y) {
if(x == y - 1) return true;
if(x == y + 1) return false;
if(x == y) return false;
return isLessThan((x), (y-1)) || isLessThan((x-1), y);
}
Because you have made a good-faith attempt by writing your own code, and because I see this is a kind of puzzle, I'm offering you below code which has only a single recursive call rather than having two recursive calls like in your code.
I think this is as simple as it gets while satisfying the constraints.
What it does: it counts down both numbers to zero, and checks which one reaches zero first. If both reach zero at the same time, the result should be false, but simply checking whether y is zero already includes that check.
public static boolean isLessThan(int x, int y) {
if (y == 0) {
return false;
}
if (x == 0) {
return true;
}
return isLessThan(x - 1, y - 1);
}
#Andreas' answer is more efficient than the above. My aim initially was for a short, clean answer.
I've tried to create a shorter bitshift approach.
Although harder to grasp than the counting example, it has a better complexity and it has an equal amount of lines as the above code (I'm not counting that constant as I could include it inside the code at the expense of readability).
Note that this code shifts left rather than right and - it checks the most significant bit first.
public static final int HIGH_BIT = 1 << 31;
public static boolean isLessThan(int x, int y) {
if (x == y) {
return false;
}
if ((x & HIGH_BIT) != (y & HIGH_BIT)) {
return (y & HIGH_BIT) == HIGH_BIT;
}
return isLessThan(x << 1, y << 1);
}
Note: if != is disallowed, you can change the second if statement to:
if (((x ^ y) & HIGH_BIT) == HIGH_BIT)
Also note that the complexity is really O(1) as, although the algorithm is theoretically O(log n), Java ints are 32 bits so the upper bounds is O(32) which is the same as O(1).
You could do it like the answer to this question:
Bitwise operations equivalent of greater than operator
However that doesn't honor rule 2: It must be recursive.
According to comment, rule 1 should be:
You can only use plus, minus, multiply, equals, and bitwise operators.
With the use of the right-shift operator, we can get a solution in O(log n) time, unlike answer by Erwin Bolwidt, which is O(n) time, and likely to cause StackOverflowError.
public static boolean isLessThan(int x, int y) {
return compare(x, y) == -1;
}
private static int compare(int x, int y) {
if (x == y)
return 0; // x == y
if (x == 0)
return -1; // x < y
if (y == 0)
return 1; // x > y
// Compare higher bits. If different, then that is result
int cmp = compare(x >> 1, y >> 1);
if (cmp != 0)
return cmp;
// Only bit 0 differs, so two choices:
// x0 == 1 && y0 == 0 -> return 1
// x0 == 0 && y0 == 1 -> return -1
return (x & 1) - (y & 1);
}
If != is not allowed, code can be changed to:
// same code up to and including recursive call
if (cmp == 0)
return (x & 1) - (y & 1);
return cmp;

HackerRank challenge, what am I doing wrong? [closed]

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 6 years ago.
Improve this question
I am trying to do this challenge https://www.hackerrank.com/challenges/java-if-else
I tried doing this:
public class Main {
public static void main(String[] args) {
int x;
x = 34;
if ((x % 2) != 0) {
System.out.println("Weird");
} else if (((x % 2 == 0) & ((x >= 2) & (5 >= x)))) {
System.out.println("Not Weird");
} else if (((x % 2 == 0) & ((x >= 6) & (20 >= x)))) {
System.out.println("Weird");
} else if ((x % 2 == 0) & (x > 20)) {
System.out.println("Not Weird");
}
}
}
I ran this in Intellij and it works fine, but here, I only get three test cases right. What am I doing wrong? I was overwhelmed by the scanner stuff, as I have not even covered that stuff yet in my own reading.
HackerRank challenge, what am I doing wrong?
You are not reading the number from Standard Input, so the tests are all checking the output for the number 34.
Replace
int x;
x = 34;
With this (which is what the test started with)
Scanner sc=new Scanner(System.in);
int x=sc.nextInt();
Do that, your tests pass fine.
Alternate solution
boolean even = x % 2 == 0;
boolean weird = !even || (even && (6 <= x && x <= 20));
System.out.println(weird ? "Weird" : "Not Weird");
You should be using && as a conditional operator. Also you don't need to have the if statement check if it is even, as the first if statement provided in their code already checks if it's odd. If it isn't (only other option is even) it goes to the else statement. Elegant solution listed below.
The scanner simply is just what is passed in, don't worry about it, just use the value n, they will pass the value into the code.
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
String ans="";
if(n%2==1){ // only if it's odd
ans = "Weird";
}
// only enters else if the value is even
else{
if (n >= 6 && n <= 20) { // between 6 and 20
ans = "Weird";
} else { // only other option is greater than 20
// or below 6 which includes 2 through 5
ans = "Not Weird";
}
}
System.out.println(ans);
}
EDIT: Saw that his ranges are in a non-traditional order, so it is fine. Not sure what was wrong prior.
The above answer is better^^
I cannot comment (rep too low), but you don't need to check if it is even each time after the first check. You can assume that if it is not odd, then it is even.
An easier/simpler way of writing your code is:
String answer = "";
if ((x % 2) != 0) {//if odd
answer = "Weird";
}
else { //if even
if ((x > 1) && (x < 6)) {
answer = "Not Weird";
}
else if ((x > 5) && (x < 21)) {
answer = "Weird";
}
else if (x > 20) {
answer = "Not Weird";
}
System.out.println(answer);
By not using "equal to" operators and changing your order in the "less than" side you could solve your problem.
Your code is OK, has passed HackerRank tests, inside their else:
if ((n % 2 == 0) & ((n >= 2) & (5 >= n)))
System.out.println("Not Weird");
if ((n % 2 == 0) & ((n >= 6) & (20 >= n)))
System.out.println("Weird");
if ((n % 2 == 0) & (n > 20))
System.out.println("Not Weird");
Just changed to "else if" to "if".

Categories