+ 1

How to find whether a number is positive or negative without using if() statements or any conditional statement

conditional statement like ternary operator are not allowed

1st Sep 2017, 3:30 PM
Pranav Singh Sehgal
9 odpowiedzi
+ 14
System.out.println(number != Math.abs(number));
1st Sep 2017, 3:36 PM
Hatsy Rei
Hatsy Rei - avatar
+ 12
Actually Gavin should have had the shortest answer. System.out.println(number < 0);
1st Sep 2017, 3:54 PM
Hatsy Rei
Hatsy Rei - avatar
+ 5
@Gavin You don't need the ternary operator number<0 will give the same result. 😉
1st Sep 2017, 3:51 PM
ChaoticDawg
ChaoticDawg - avatar
+ 5
Math.abs() uses ternary. 😜 Could also do: boolean isPositive = (myNum >> 31 == 0);
1st Sep 2017, 3:59 PM
Rrestoring faith
Rrestoring faith - avatar
+ 5
@Restoring faith I like your bitwise check, but you could just == instead of negating the result. myNum >> 31 == 0 a little easier to read and understand imo either way it's a cool check 👍
1st Sep 2017, 4:11 PM
ChaoticDawg
ChaoticDawg - avatar
+ 4
@Chaotic Oops, nice read.
1st Sep 2017, 4:13 PM
Rrestoring faith
Rrestoring faith - avatar
+ 2
public class Program { public static void main(String[] args) { int number = -1; boolean negative; negative=number<0?true:false; System.out.println(negative); } }
1st Sep 2017, 3:34 PM
Ghauth Christians
Ghauth Christians - avatar
+ 1
Nice one @Hatsy ☺
1st Sep 2017, 3:39 PM
Ghauth Christians
Ghauth Christians - avatar
+ 1
That's correct @ChaoticDawg but I wanted @Pranav to be curious as to why I used that.
1st Sep 2017, 3:54 PM
Ghauth Christians
Ghauth Christians - avatar