๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
Algorithm

[Algorithm] ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค Lv.1 : ๋‘ ์ •์ˆ˜ ์‚ฌ์ด์˜ ํ•ฉ

by ์ฝ”๋”ฉ๊ณต์ฑ… 2022. 11. 5.
๋ฐ˜์‘ํ˜•

๋‘ ์ •์ˆ˜ ์‚ฌ์ด์˜ ํ•ฉ

๋‘ ์ •์ˆ˜ 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 12

๋ฌธ์ œ ํ’€์ด

if, else if๋ฌธ์„ ํ†ตํ•ด a์™€ b๊ฐ€ ๊ฐ™์€ ๊ฒฝ์šฐ๋Š” a๋ฅผ ์ถœ๋ ฅ์‹œํ‚ค๊ณ  a๋ณด๋‹ค b๊ฐ€ ํฐ ๊ฒฝ์šฐ๋Š” a+(a+1)+b๋ฅผ, a๊ฐ€ ๋” ํฐ ๊ฒฝ์šฐ๋Š” a+(a-1)+b๋ฅผ answer์— ์ €์žฅ์‹œ์ผœ ์ตœ์ข…์ ์œผ๋กœ 3+4+5, 5+4+3์ด ์ €์žฅ๋˜๋„๋ก ์ฝ”๋”ฉํ•˜์˜€๋‹ค.

#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>

long long solution(int a, int b) {
    long long answer = 0;
    
    if(a==b){
        answer = a;	//3
    } else if(a<b){
        answer = a+(a+1)+b;	//12
    } else {
        answer = a+(a-1)+b;	//12
    }
    return answer;
}

๋‹ค๋ฅธ ํ’€์ด ๋ฐฉ์‹

์ถœ์ฒ˜ : ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค ์Šค์ฟจ

int A์—๋Š” a๋ณด๋‹ค b๊ฐ€ ๋” ํฌ๋ฉด a๋ฅผ, ๊ทธ๋ ‡์ง€ ์•Š์œผ๋ฉด b๋ฅผ ์ถœ๋ ฅํ•˜๋„๋ก ํ•˜๊ณ  int B๋Š” ๊ทธ ๋ฐ˜๋Œ€๋กœ ์ถœ๋ ฅํ•˜๋„๋ก ํ•œ๋‹ค. ๊ทธ๋Ÿฐ ๋‹ค์Œ for๋ฌธ์„ ์ด์šฉํ•˜์—ฌ int i์— A๊ฐ’์„ ์ €์žฅ์‹œํ‚ค๊ณ  i๊ฐ€ B๋ณด๋‹ค ์ž‘๊ฑฐ๋‚˜ ๊ฐ™์„ ๋•Œ๊นŒ์ง€ i๊ฐ’์„ ์ฆ๊ฐ€์‹œํ‚ค๊ฒŒ ํ•˜์—ฌ answer์— ์ฆ๊ฐ€๋˜๋Š” i๊ฐ’์„ ์ €์žฅ์‹œํ‚จ๋‹ค. ์ตœ์ข…์ ์œผ๋กœ 3+4+5 / 5+4+3์ด ์ €์žฅ๋˜๊ณ  A,B์˜ ๊ฐ’์ด ๊ฐ™์„ ๊ฒฝ์šฐ์—๋Š” b ๋˜๋Š” a๊ฐ€ ์ถœ๋ ฅ๋˜๊ธฐ ๋•Œ๋ฌธ์— 3์ด ์ถœ๋ ฅ๋œ๋‹ค.

#include <stdio.h>

long long solution(int a, int b)
{
    long long answer = 0;

    int A = a < b ? a : b;
    int B = a < b ? b : a;

    for (int i = A; i <= B; i++)
    {
        answer += i;
    }



    return answer;
}
๋ฐ˜์‘ํ˜•

๋Œ“๊ธ€


Reference Book

JavaScript
HTML
CSS
๊ด‘๊ณ  ์ค€๋น„์ค‘์ž…๋‹ˆ๋‹ค.