본문 바로가기

코딩테스트/Coding Bat

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

728x90
728x90

https://codingbat.com/prob/p101887

 

CodingBat Java Warmup-1 intMax

Given three int values, a b c, return the largest.intMax(1, 2, 3) → 3intMax(1, 3, 2) → 3intMax(3, 2, 1) → 3Go...Save, Compile, Run (ctrl-enter)Show Solution

codingbat.com



= 문제 번역 =

세 개의 int 값 b c가 주어지면 가장 큰 값을 반환합니다.

 

= 문제푸는 팁 =

1번 해설로 문제 풀 때, if의 Max부분에 a를 넣고 풀었다가, 오답이 나왔다. c와 Max를 구분해야 확실히 정답이 나온다는 것 주의하기!

 

= 해설 =

< 1 >
public int intMax(int a, int b, int c) {
  int Max = a;
  if(b>Max){
    Max=b;
  }
  if(c>Max){
    Max=c;
  }
  return Max;
}

< 2 >
public int intMax(int a, int b, int c) {
  int max;
  
  // First check between a and b
  if (a > b) {
    max = a;
  } else {
    max = b;
  }
  
  // Now check between max and c
  if (c > max) {
    max = c;
  }
  
  return max;
  
  // Could use the built in Math.max(x, y) function which selects the larger
  // of two values.
}

728x90