diff21

Programming problem at

http://codingbat.com/prob/p116624

Given an int n, return the absolute difference between n and 21, except return double the absolute difference if n is over 21.
diff21(19) → 2
diff21(10) → 11
diff21(21) → 0

My Solution

First i wrote

public int diff21(int n) {
  int absDiff = java.Math.abs(n-21);
  if(n>21)
  absDiff =  2*absDiff;
  return absDiff;
}

 

It gave error that java.Math cannot be resolved to a type. Then i realized i should not use java build in packages

Then i modified correct the code as

public int diff21(int n) {
  int absDiff = n-21;
  if (absDiff < 0 )
  absDiff = (-1)*absDiff;
  if(n>21)
  absDiff =  2*absDiff;
  return absDiff;
}

 

After i read the coding rules ( see Comparison and Lessons below ) , i realized that packages are allowed to be imported

However my mistake was different , i wrote wrong java class package.

The revised correct code with build in function of abs is

public int diff21(int n) {
  int absDiff = java.lang.Math.abs(n-21);
  if(n>21)
  absDiff =  2*absDiff;
  return absDiff;
}

 

The official solution was

 

public int diff21(int n) {
if (n <= 21) {
return 21 - n;
} else {
return (n - 21) * 2;
}
}

Comparison and Lessons

I read the coding rules for CodingBat website (http://codingbat.com/help.html)  The java.util package is included in all the problems

My second mistake was to use the wrong java.lang.Math package ( i used java.Math )

Other thing which i noticed specific to CodingBat is below

If the method takes a String or array argument, those arguments will not be passed in a null. However, the empty String or array is still a valid case unless the problem statement specifically says otherwise.

Lessons learnt to remember the java Math class package

No comments:

Post a Comment

Please share your views and comments below.

Thank You.