본문 바로가기

코딩테스트/Coding Bat

[코딩뱃] [자바] Warmup - 1단계 : close10 문제

728x90
728x90

https://codingbat.com/prob/p172021

 

CodingBat Java Warmup-1 close10

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) → 8close10(13, 8) → 8close10(13, 7) → 0Go...Save, Compile, Run (ctrl

codingbat.com



= 문제 번역 =

2개의 int 값이 주어지면 값 10에 가장 가까운 값을 반환하거나 동점인 경우 0을 반환합니다. 

Math.abs(n)은 숫자의 절대값을 반환합니다.

 

= 문제푸는 팁 =

Math.abs(a)-10을 해야할지 Math.abs(a-10)을 해야하는지 잘 구분할 것!

 

= 해설 =

< 1 >
public int close10(int a, int b) {
  if(Math.abs(a-10)>Math.abs(b-10)){
    return b;
  }else if (Math.abs(a-10)==Math.abs(b-10)){
    return 0;}
    else return a;
}

< 2 >
public int close10(int a, int b) {
  int aDiff = Math.abs(a - 10);
  int bDiff = Math.abs(b - 10);
  
  if (aDiff < bDiff) {
    return a;
  }
  if (bDiff < aDiff) {
    return b;
  }
  return 0;  // i.e. aDiff == bDiff
  
  // Solution notes: aDiff/bDiff local vars clean the code up a bit.
  // Could have "else" before the second if and the return 0.
}

728x90