Java > Warmup-1 > close10 (CodingBat Solution)

Problem:

Given 2 int values, return whichever value is nearest to the value 10, or return 0 in the event of a tie. Note that Math.abs(n) returns the absolute value of a number.

close10(8, 13) → 8
close10(13, 8) → 8
close10(13, 7) → 0


Solution:

public int close10(int a, int b) {
  int temp1 = Math.abs(a - 10);
  int temp2 = Math.abs(b - 10);

  if (temp1 == temp2)
    return 0;
  else if (temp1 > temp2)
    return b;
  else 
    return a;
}


1 comment :

  1. public int close10(int a, int b) {
    int c = Math.abs(b-10);
    int d = Math.abs(a-10);
    return (c == d) ? 0 : ((a < b) ? a : b);
    }

    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