1 minute read

๐Ÿ“ˆ What I learned after solving the algorithm questions.

Approach:

์•ฝ์ˆ˜(divisor)๋ž€ ์ˆซ์ž๋ฅผ ๋‚˜๋ˆ„์—ˆ์„ ๋•Œ ๋‚˜๋ˆ„์–ด ๋–จ์–ด์ง€๊ฒŒ ํ•˜๋Š” ์ˆ˜์ด๋ฏ€๋กœ ๋‚˜๋จธ์ง€๊ฐ€ 0์ธ ์ˆ˜๋ฅผ ๋ชจ๋‘ ๊ตฌํ•ด์„œ ๋”ํ•˜๋ฉด ๋œ๋‹ค.

Solution:

modulus ์‚ฌ์šฉํ•ด์„œ n์˜ ๋‚˜๋จธ์ง€ ๊ฐ’์„ ๊ตฌํ•œ๋‹ค. ๋งŒ์•ฝ ๋‚˜๋จธ์ง€๊ฐ€ 0์ด๋ฉด answer์— ๋”ํ•ด์ค€๋‹ค. ์ด ๋•Œ, ๋‚˜๋ˆ„๋Š” ์ˆ˜ x๋Š” n๋ณด๋‹ค ์ž‘๊ฑฐ๋‚˜ ๊ฐ™๋‹ค.

Code 1: using if statement

public class Solution4 {
    public int solution(int n) {
        int answer = 0;
        int x;
        for(x=1;x<=n;x++){
            if(n % x == 0){
                answer+=x;
            }
        }
        return answer;
    }

    public static void main(String[] args) {
        Solution4 solution4 = new Solution4();
        int answer = solution4.solution(12);
        System.out.println("answer = " + answer);
    }
}

What I learned:

๋งค์šฐ ๊ฐ„๋‹จํ•˜๊ฒŒ ํ’€์–ด์„œ ์ข‹์•„ํ–ˆ๋Š”๋ฐ ๋‹ค๋ฅธ ์‚ฌ๋žŒ์˜ ํ’€์ด๋ฅผ ๋ณด๊ณ  ๋†€๋ž๋‹ค. ์ฃผ์–ด์ง„ ์ˆ˜๋ฅผ 2๋กœ ๋‚˜๋ˆ„๋ฉด ๊ทธ๋ฅผ ์ดˆ๊ณผํ•˜๋Š” ์ˆ˜์—์„œ๋Š” ์ž๊ธฐ ์ž์‹  ๋ง๊ณ ๋Š” ๋”์ด์ƒ ์•ฝ์ˆ˜๊ฐ€ ์—†๋‹ค. ๊ทธ๋Ÿฌ๋ฏ€๋กœ for loop์„ ๋Œ๋ฆด ๋•Œ n๋งŒํผ ๋Œ๋ฆฌ์ง€ ๋ง๊ณ  n/2๋งŒํผ๋งŒ ๋Œ๋ ค์ฃผ๋ฉด ์ฃผ์–ด์ง„ ์ˆ˜๋ฅผ ์ œ์™ธํ•œ ๋ชจ๋“  ์•ฝ์ˆ˜๋ฅผ ๊ตฌํ•  ์ˆ˜ ์žˆ๋‹ค. ์ด ๋ชจ๋“  ์•ฝ์ˆ˜๋“ค์„ ๋”ํ•ด์ฃผ๊ณ  ๋งˆ์ง€๋ง‰์— ์ฃผ์–ด์ง„ ์ˆ˜๋ฅผ ๋”ํ•ด์ฃผ๋ฉด ํ•ฉ์„ ๊ตฌํ•  ์ˆ˜ ์žˆ๋‹ค. ๋ฐ˜๋ณต๋ฌธ์„ ๋ฐ˜์œผ๋กœ ์ค„์ผ ์ˆ˜ ์žˆ๋Š” ๋ฐฉ๋ฒ•์ด๋‹ค.

Code refactored: less looping

public class Solution4 {
    public int solution(int n) {
        int answer = 0;
        int x;
        for(x=1;x<=n/2;x++){
            if(n % x == 0){
                answer+=x;
            }
        }
        return answer+n;
    }

    public static void main(String[] args) {
        Solution4 solution4 = new Solution4();
        int answer = solution4.solution(12);
        System.out.println("answer = " + answer);
    }
}

Leave a comment