Java > Warmup-1 > posNeg (CodingBat Solution)

Problem:

Given 2 int values, return true if one is negative and one is positive. Except if the parameter "negative" is true, then return true only if both are negative.

posNeg(1, -1, false) → true
posNeg(-1, 1, false) → true
posNeg(-4, -5, true) → true


Solution:

public boolean posNeg(int a, int b, boolean negative) {
  if (negative && a < 0 && b < 0)
    return true;
  else if (!negative && a < 0 && b > 0)
    return true;
  else if (!negative && a > 0 && b < 0)
    return true;
  else
    return false; 
   
}


3 comments :

  1. public boolean posNeg(int a, int b, boolean negative) {
    return negative && a < 0 && b < 0
    || !negative && a < 0 && b > 0
    || !negative && a > 0 && b < 0;
    }

    ReplyDelete
  2. public boolean posNeg(int a, int b, boolean negative) {
    return negative && a < 0 && b < 0 || !negative && (a < 0 && b > 0 || a > 0 && b < 0);
    }

    ReplyDelete
  3. public boolean posNeg(int a, int b, boolean negative) {
    return (negative && a < 0 && b < 0)
    || (!negative && a != 0 && b != 0) && (a <= 0) == (b >= 0);
    }

    ReplyDelete

Follow Me

If you like our content, feel free to follow me to stay updated.

Subscribe

Enter your email address:

We hate spam as much as you do.

Upload Material

Got an exam, project, tutorial video, exercise, solutions, unsolved problem, question, solution manual? We are open to any coding material. Why not upload?

Upload

Copyright © 2012 - 2014 Java Problems  --  About  --  Attribution  --  Privacy Policy  --  Terms of Use  --  Contact