https://programmers.co.kr/learn/courses/30/lessons/12912
์ฝ๋ฉํ ์คํธ ์ฐ์ต - ๋ ์ ์ ์ฌ์ด์ ํฉ | ํ๋ก๊ทธ๋๋จธ์ค
๋ ์ ์ a, b๊ฐ ์ฃผ์ด์ก์ ๋ a์ b ์ฌ์ด์ ์ํ ๋ชจ๋ ์ ์์ ํฉ์ ๋ฆฌํดํ๋ ํจ์, solution์ ์์ฑํ์ธ์. ์๋ฅผ ๋ค์ด a = 3, b = 5์ธ ๊ฒฝ์ฐ, 3 + 4 + 5 = 12์ด๋ฏ๋ก 12๋ฅผ ๋ฆฌํดํฉ๋๋ค. ์ ํ ์กฐ๊ฑด a์ b๊ฐ ๊ฐ์ ๊ฒฝ์ฐ๋ ๋ ์ค ์๋ฌด ์๋ ๋ฆฌํดํ์ธ์. a์ b๋ -10,000,000 ์ด์ 10,000,000 ์ดํ์ธ ์ ์์ ๋๋ค. a์ b์ ๋์๊ด๊ณ๋ ์ ํด์ ธ์์ง ์์ต๋๋ค. ์ ์ถ๋ ฅ ์ a b return 3 5 12 3 3 3 5 3
programmers.co.kr
์ฒ์ ํผ ํ์ด
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
class Solution {
public long solution(int a, int b) {
long answer = 0;
if(a<b){//a๊ฐ b๋ณด๋ค ์์ ๋
for(int i=a; i<=b ; i++){
answer+=i;
}
}else if(a>b){//a๊ฐ b๋ณด๋ค ํด ๋
for(int i=b; i<=a ; i++){
answer+=i;
}
}else{//a=b๊ฐ ๊ฐ์ ๋
answer=a;
}
return answer;
}
}
|
cs |
์๊ฐ๊ณผ์
- a๊ฐ b๋ณด๋ค ์์ ๋, ํด ๋, ๊ฐ์ ๋ ๋ก ๋๋๋ค.
- a๊ฐ b๋ณด๋ค ์์ ๋๋ for์ ๋ฒ์๋ฅผ for(int i=b; i<=a ; i++)๋ก ์ก์ a๋ก ์์ํด์ ํ๋์ฉ ๋๋ ค b๊น์ง answer์ ๋ํด์ค๋ค.
- a๊ฐ b๋ณด๋คํด ๋ ๋ for์ ๋ฒ์๋ฅผ for(int i=b; i<=a ; i++) ๋ก ์ก์ b๋ก ์์ํด์ ํ๋์ฉ ๋๋ ค a๊น์ง answer์ ๋ํด์ค๋ค.
- ๊ฐ์๋๋ ๋์ค์ ์๋ฌด๊ฐ์ด๋ ํ๋ ๋ฐํํด์ค๋ค.
2. ๋ค๋ฅธ ์ฌ๋์ ํ์ด๋ฅผ ๋ณด๊ณ ํผ ํ์ด
1
2
3
4
5
6
7
8
9
10
|
class Solution {
public long solution(int a, int b) {
long answer = 0;
for(int i= (a>b ? b : a); i<=(a>b ? a : b); i++) //์ผํญ์ฐ์ฐ์
answer+=i;
return answer;
}
}
|
cs |
- for๋ฌธ ์์ ์ผํญ์ฐ์ฐ์๋ฅผ ์ด์ฉํ์ฌ ํ์ดํ๋ค.
- ๋์ค์ ๋ค๋ฅธ ๋ฌธ์ ์์๋ ์ฌ์ฉ ํด๋ด์ผ๊ฒ ๋ค.
'JAVA > ํ๋ก๊ทธ๋๋จธ์ค' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
์๋ฐ์๋ฐ์๋ฐ์๋ฐ์๋ฐ์?/Java/ํ๋ก๊ทธ๋๋จธ์ค (0) | 2020.02.07 |
---|---|
์์ ์ฐพ๊ธฐ /ํ๋ก๊ทธ๋๋จธ์ค/์๋ฐ/level1/์๋ผํ ์คํ ๋ค์ค์ ์ฒด (0) | 2020.02.05 |
์์ธ์์ ๊น์๋ฐฉ ์ฐพ๊ธฐ /Java/Level1/ํ๋ก๊ทธ๋๋จธ์ค (0) | 2020.02.04 |
[ Java Level 1 ] ๋ฌธ์์ด ๋ด p์ y์ ๊ฐ์ (0) | 2020.02.04 |
[Java Level 1]๊ฐ์ด๋ฐ ๊ธ์ ๊ฐ์ ธ์ค๊ธฐ (0) | 2020.02.03 |