01-09 04:37
Recent Posts
Recent Comments
๊ด€๋ฆฌ ๋ฉ”๋‰ด

miinsun

[Programmers] ์ˆซ์ž์˜ ํ‘œํ˜„ - JAVA (์Šฌ๋ผ์ด๋”ฉ ์œˆ๋„์šฐ, ํˆฌํฌ์ธํ„ฐ) ๋ณธ๋ฌธ

Algorithm/Programmers

[Programmers] ์ˆซ์ž์˜ ํ‘œํ˜„ - JAVA (์Šฌ๋ผ์ด๋”ฉ ์œˆ๋„์šฐ, ํˆฌํฌ์ธํ„ฐ)

miinsun 2022. 5. 19. 00:56

 

๐Ÿ’ฌ ๋ฌธ์ œ ์„ค๋ช…

Finn์€ ์š”์ฆ˜ ์ˆ˜ํ•™๊ณต๋ถ€์— ๋น ์ ธ ์žˆ์Šต๋‹ˆ๋‹ค. ์ˆ˜ํ•™ ๊ณต๋ถ€๋ฅผ ํ•˜๋˜ Finn์€ ์ž์—ฐ์ˆ˜ n์„ ์—ฐ์†ํ•œ ์ž์—ฐ์ˆ˜๋“ค๋กœ ํ‘œํ˜„ ํ•˜๋Š” ๋ฐฉ๋ฒ•์ด ์—ฌ๋Ÿฌ๊ฐœ๋ผ๋Š” ์‚ฌ์‹ค์„ ์•Œ๊ฒŒ ๋˜์—ˆ์Šต๋‹ˆ๋‹ค.

์˜ˆ๋ฅผ๋“ค์–ด 15๋Š” ๋‹ค์Œ๊ณผ ๊ฐ™์ด 4๊ฐ€์ง€๋กœ ํ‘œํ˜„ ํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.
* 1 + 2 + 3 + 4 + 5 = 15
* 4 + 5 + 6 = 15
* 7 + 8 = 15
* 15 = 15

์ž์—ฐ์ˆ˜ n์ด ๋งค๊ฐœ๋ณ€์ˆ˜๋กœ ์ฃผ์–ด์งˆ ๋•Œ, ์—ฐ์†๋œ ์ž์—ฐ์ˆ˜๋“ค๋กœ n์„ ํ‘œํ˜„ํ•˜๋Š” ๋ฐฉ๋ฒ•์˜ ์ˆ˜๋ฅผ returnํ•˜๋Š” solution๋ฅผ ์™„์„ฑํ•ด์ฃผ์„ธ์š”.

 

๐Ÿšซ ์ œํ•œ ์‚ฌํ•ญ

    • n์€ 10,000 ์ดํ•˜์˜ ์ž์—ฐ์ˆ˜ ์ž…๋‹ˆ๋‹ค.

๐Ÿ”จ ์ž…์ถœ๋ ฅ ์˜ˆ

 

๐Ÿ’ป Solution.java

  • ํˆฌ ํฌ์ธํ„ฐ i, j ๋ฅผ ์ด์šฉํ•œ๋‹ค.
    • ํฌ์ธํ„ฐ i๋Š” ์•ž์„œ๊ฐ€๊ณ , ํฌ์ธํ„ฐ j๋Š” i ๋’ค๋ฅผ ๋”ฐ๋ผ๊ฐ„๋‹ค.
      • sum ๊ฐ’์ด n๋ณด๋‹ค ์ž‘๊ฑฐ๋‚˜ ๊ฐ™์œผ๋ฉด i๋งŒํผ sum์— ๋”ํ•ด์ฃผ๊ณ 
      • sum์˜ ๊ฐ’์ด n๋ณด๋‹ค ์ปค์ง€๋ฉด j๋งŒํผ sum์—์„œ ๋นผ์ฃผ์ž
class Solution {
    public int solution(int n) {
        int answer = 0;

        int sum = 0;
        int i = 1, j = 1;

        while(i <= n  || j <= n) {
            if(sum <= n) {
                sum += i++;
            }
            else if (sum > n){
                sum -= j++;
            }	        

            if(sum == n)
                answer++;
        }

        return answer;
    }
}

 

Comments