Friday, June 3, 2016

Java Challenge - nearHundred - warm_up

Given an int n, return true if it is within 10 of 100 or 200. Note: Math.abs(num) computes the absolute value of a number.

nearHundred(93) → true
nearHundred(90) → true
nearHundred(89) → false

Hisoka's code:
1
2
3
public boolean nearHundred(int n) {
  return((Math.abs(n-100) <= 10)||(Math.abs(200-n) <= 10));
}

Output:

Codingbat code:
1
2
3
4
public boolean nearHundred(int n) {
  return ((Math.abs(100 - n) <= 10) ||
    (Math.abs(200 - n) <= 10));
}

Hohoho... Mirip... :D

Java Challenge - posNeg - warm_up

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

Hisoka's Style:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
public boolean posNeg(int a, int b, boolean negative) {
  if(negative)
  {
    if(a<0 && b<0) return true;
    else return false;
  }else
  {
    if((a<0 && b>0) || (a>0 && b<0)) return true;
    else return false;
  }
 
}

Output:

Codingbat style:
1
2
3
4
5
6
7
8
public boolean posNeg(int a, int b, boolean negative) {
  if (negative) {
    return (a < 0 && b < 0);
  }
  else {
    return ((a < 0 && b > 0) || (a > 0 && b < 0));
  }
}