Java simplify the syntax - java

What would be the most terse way in Java to check for the following condition
int m, n;
The condition to check is whether either m or n are negative but both shouldn't be negative. I'm looking for a terse yet simple syntax

(m < 0) ^ (n < 0)
Note that in this context, ^ is the logical XOR operator (yes, I do mean "logical", distinct from "bitwise").

(m ^ n) < 0
Even more filler to make an appropriate length answer.

I'd go for:
(m < 0) != (n < 0)
!= operates the same as ^ for booleans, but I think it's easier to understand and more commonly used.

Basically your test should be - the sign bit (highest order) shound be different.
Here is the test expressed in java;
if ( (x & Integer.MIN_VALUE) != (y & Integer.MIN_VALUE) )
...

Related

Java: weird behavior of conditional operator

I have a very simple java class to solve Decode ways using recursive approach. I am seeing this weird behavior of conditional operator,
package decodeways;
public class Solution {
public static void main(String[] args) {
System.out.println(numDecodings("1456"));
}
public static int numDecodings(String s) {
if(s.length()>0 && s.charAt(0)=='0')
return 0;
if(s.length()==0) return 1;
if(s.length()==1)
return 1;
int num1 = s.charAt(0)-'0';
int num2 = s.charAt(1)-'0';
int one = numDecodings(s.substring(1));
int two = s.length()>1?numDecodings(s.substring(2)):0;
int res = one
+ num1<3 && num2<7 ? two:0;
return res;
}
}
if I put a parentheses, (num1<3 && num2<7 ? two:0) then everything is well and good but if I remove the parentheses, then getting incorrect results.
during the process of debugging, one will be computed to 1 and two will be computed to 1 and res will be 1 as well with parentheses but without it, the computed result of res will be 0 (screnshot attached) which is the source of error.
I am aware of the operator precedence in java, but in this situation I can't figure out why it shows incorrect behavior, because in the below code:
int res = one
+ num1<3 && num2<7 ? two:0;
one + num1<3 is illegal
So, java is intelligent enough to not confuse between (one + num1<3) and (num2<7 ? two:0) to be consider separately.
So, as per my understanding the only legal observable behavior for java compiler is to automatically consider num1<3 && num2<7 ? two:0 as an atomic operation(Please correct me if I am wrong), irrespective of parentheses is available or not.
Please guide me to have a better understanding.
Thanks.
int res = one
+ num1<3 && num2<7 ? two:0;
is equivalent to
int res = (((one + num1) < 3) && (num2 < 7)) ? two : 0;
Everything before ? is included in the boolean expression, since the ternary/conditional operator has the lowest precedence here (not including the assignment operator) and + has the highest.
The order goes something like:
+, so one + num1 is put together first
<, so now there's (one + num1) < 3 and num2 < 7
&&, after which you have ((one + num1) < 3) && (num2 < 7)
and finally ?:
You seem to be expecting the newline to make the compiler think one and num1<3 && num2<7 ? two:0 are separate, but it actually just ignores all whitespace. Putting the parentheses there is the only way to make sure one is added to the whatever the conditional operator evaluates to.
int res = one + (num1 < 3 && num2 < 7 ? two : 0);

Converting C statement in to Java (Array[][] != 0)

I'm changing some C code into Java, but I have come across a statement syntax that I have not seen before and I don't know what it means.
for (unsigned int i = 0; i < SIZE; i++)
{
count[2 * SIZE + 1] += grid[i][SIZE - 1 - i] != 0;
}
When adding elements of two arrays, I've never seen '!= 0' come after it. Do you know what this statement is doing? I can't find any reference to this online.
Any help is appreciated.
grid[i][SIZE - 1 - i] != 0 is a boolean expression which (by the C standard) is evaluated to 1 if the expression is true, 0 otherwise.
The same thing can be written as following:
for (unsigned int i = 0; i < SIZE; i++)
{
if ( grid[i][SIZE - 1 - i] != 0)
{
count[2 * SIZE + 1] += 1;
}
}
Unlike in C/C++, in Java, the result of this test is a boolean not an integer (0/1), and you cannot add a boolean so it counts for 0 for false or 1 for true.
I suggest a simple test which avoids to add 0 to count uselessly. So probably faster (well, constant branching could make it slower, has to be benched) & less cryptic (that's a fact), and valid in C, C++ or Java:
if (grid[i][SIZE - 1 - i] != 0)
{
count[2 * SIZE + 1]++;
}
Booleans can be implicitly converted to integers.
It is equivalent to
(grid[i][SIZE - 1 - i] != 0) ? 1 : 0
that is, add 1 if the condition is true and zero otherwise.

Weird bit shifting behaviour

I was attempting the powerset problem with iteration and bit shifting.
There is a particular behaviour I am unable to comprehend.
I would have expected all the 3 statement below to indicate testing if jth bit in i is set.
Why are the results different then?
private static void printSubsetInBit(Integer[] arr) {
for(int i=0;i<(1<<arr.length);i++){
List<Integer> pack=new ArrayList<Integer>();
for(int j=0;j<arr.length;j++){
//if(((i>>j)&1)==1){ -->>>> WORKS
//if((i & ( 1<<j))>0){-->>>> WORKS
if((i & ( 1<<j))==1){ -->>>> DOES NOT WORK
pack.add(arr[j]);
}
}
System.out.println(pack.toString());
}
}
If you left-shift 1 by j and then use it to mask i, you have to compare the result to the result of left-shifting 1 by j, not to 1.
In other words the condition should be
((i & (1 << j)) == (1 << j))
Or just "!= 0" would be fine.
(i & ( 1<<j))==1 is false unless j == 0, because ((1<<j) & 1 == 0) == (j != 0) (*).
This is simply not equivalent to the other expressions.
(*) Well, j % 32 == 0/j % 32 != 0; the second operand is masked.

basic if statement, operator <= undefined

I'm new to programming
if( (N%2==0) && (6<=N<=20) )
Throws the error below
The operator <= is undefined for the argument type(s) boolean, int
Please help me fix it.
You can't compound the statement like that. You need to && it.
For example,
if ((N % 2 == 0) && (6 <= N && N <= 20)) {...}
The reason you get the error is the first condition of 6 <= N resolves to a boolean and you then attempt to check if a boolean is <= to an int. That does not compute.
You can't compare 2 conditions in one check, you need to split it to two checks
if (N % 2 == 0 && N >= 6 && N <= 20)
You should separate the conditions with logical operators (&& in this case):
if (N % 2 == 0 && N>=6 && N <= 20)

Java expression type

I saw a question on Java manuals that keeps grinding my gear so i'm posting it here to solve it once and for all.
The question is:
If n and k are int type then what type would ' n > k && k < 0 ' expression be?
Possible answers : byte, boolean, int, double, won't compile.
Thank you for your advice on it.
An easy way to check is just to print it using for example Ideone. Check this link to see a demonstration.
That said, the expression evaluates to a boolean. Since < and > have higher precedence than &&, the expression is equivalent to (n > k) && (k < 0), which is a bit easier to interpret.
boolean
This expression is usually used in a condition and return true or false.
It is boolean because : (n > k && k < 0)
n > k return boolean
k < 0 return boolean
boolean && boolean is boolean

Categories