728x90
TIP
์ฐจ์ด๊ฐ์ ์ ๋๊ฐ์ ์ต์๊ฐ ์๊ณ ๋ฆฌ์ฆ์ ์ ์ฉํด์ฃผ๋ฉด ๋๋ค.
์ฐจ์ด๊ฐ์ ์ ๋๊ฐ์ ๋ด์์ค min ๋ณ์์
๊ฒฐ๊ณผ๊ฐ ๋ด๊ธธ near ๋ณ์๊ฐ ํ์ํ๋ค๋ ๊ฒ์ด ์ค์ ํฌ์ธํธ์ธ ์๊ณ ๋ฆฌ์ฆ!
์๋ฐ
import java.util.Arrays;
public class App {
public static void main(String[] args) throws Exception {
//[1] Initialize
int min = Integer.MAX_VALUE;
//[2] Input
int [] numbers = {23,56,65,2,2,3,3};
int target = 25;
int near = 0;
//[3] Process : MAX
for(int x : numbers) {
if(Math.abs(target - x) < min){
min = target - x;
near = x;
}
}
//[4] Output
System.out.println(near); //23
}
}
ํ์ด์ฌ
numbers = [23,56,65,2,2,3,3]
min = numbers[0]
target = 25;
near = 0
for x in range(len(numbers)):
if abs(target - numbers[x]) < min :
min = target - numbers[x]
near = numbers[x]
print(near)
abs๋ก ์ง์ ๊ตฌํํ๋ฉด ์๋์ ๊ฐ๋ค.
public class App {
public static int abs(int x){
return x > 0 ? x: x*-1;
}
public static void main(String[] args) throws Exception {
//[1] Initialize
int min = Integer.MAX_VALUE;
//[2] Input
int [] numbers = {23,56,65,2,2,3,3};
int target = 25;
int near = 0;
//[3] Process : MAX
for(int x : numbers) {
if(min > abs(target - x)) {
min = abs(target - x);
near = x;
}
}
//[4] Output
System.out.println(near); //23
}
}
ํ์ด์ฌ
numbers = [23,56,65,24,2,3,3]
def userAbs(a):
if a > 0 :
return a
return -a
min = numbers[0]
target = 25;
near = 0
for x in range(len(numbers)):
if userAbs(target - numbers[x]) < min :
min = target - numbers[x]
near = numbers[x]
print(near)
728x90
'Java & Spring > Java Algorithm' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[์๋ฐ/ํ์ด์ฌ ์๊ณ ๋ฆฌ์ฆ] ์ ํ ์ ๋ ฌ ์๊ณ ๋ฆฌ์ฆ (0) | 2022.12.19 |
---|---|
[์๋ฐ/ํ์ด์ฌ ์๊ณ ๋ฆฌ์ฆ] ์์ ์๊ณ ๋ฆฌ์ฆ (0) | 2022.12.19 |
[์๋ฐ/ํ์ด์ฌ ์๊ณ ๋ฆฌ์ฆ] ์ต๋๊ฐ ์๊ณ ๋ฆฌ์ฆ (0) | 2022.12.17 |
[์๋ฐ/ํ์ด์ฌ ์๊ณ ๋ฆฌ์ฆ] ํฉ๊ณ ์๊ณ ๋ฆฌ์ฆ (1) | 2022.12.17 |
[์๋ฐ/ํ์ด์ฌ ์๊ณ ๋ฆฌ์ฆ] ํ์ต ์์ (0) | 2022.12.17 |