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
'코딩테스트 > Coding Bat' 카테고리의 다른 글
[코딩뱃] [자바] Warmup - 1단계 : max1020 문제 (0) | 2021.09.29 |
---|---|
[코딩뱃] [자바] Warmup - 1단계 : in3050 문제 (0) | 2021.09.28 |
[코딩뱃] [자바] Warmup - 1단계 : intMax 문제 (0) | 2021.09.27 |
[코딩뱃] [자바] Warmup - 1단계 : startOz 문제 (0) | 2021.09.27 |
[코딩뱃] [자바] Warmup - 1단계 : mixStart 문제 (0) | 2021.09.26 |