본문 바로가기

혼자 코딩 공부하기/프로그래머스 코딩테스트

231229 프로그래머스

수박수박수박수박수?

class Solution {
    public String solution(int n) {
        String answer = "";
        
        for(int i = 0; i < n; i++) {
            if (i % 2 == 0) {
                answer += "수";
            } else {
                answer += "박";
            }
        }
        return answer;
    }
}

 

약수의 개수와 덧셈

class Solution {
    public int solution(int left, int right) {
        int answer = 0;
        int count = 0;
        for(; left <= right; left++) {
            for(int i = 1; i <= left; i++) {
                if (left % i == 0) {
                    count++;
                }
            }
            if (count % 2 == 0) {
                answer += left;
            } else {
                answer -= left;
            }
            count = 0;
        }
        return answer;
    }
}

 

문자열 내림차순으로 정렬

import java.util.*;

class Solution {
    public String solution(String s) {
        String answer = "";
        ArrayList<String> list = new ArrayList<>();
        ArrayList<String> list2 = new ArrayList<>();
        
        for(int i = 0; i < s.length(); i++) {
            if (Character.isUpperCase(s.charAt(i))) {
                list.add(String.valueOf((s.charAt(i))));
            } else {
                list2.add(String.valueOf(s.charAt(i)));
            }
        }
        Collections.sort(list, Collections.reverseOrder());
        Collections.sort(list2, Collections.reverseOrder());
        answer = String.join("", list);
        answer = String.join("", list2) + answer;
        
        return answer;
    }
}

 

부족한 금액 계산하기

class Solution {
    public long solution(int price, int money, int count) {
        long answer = 0;
        for(int i = 1; i <= count; i++) {
            answer += (long)(i * price);
        }
        answer -= (long) money;
        answer = answer < 0 ? 0 : answer;
        return answer;
    }
}

 

문자열 계산하기

class Solution {
    public int solution(String my_string) {
        int answer = 0;
        String[] sArr = my_string.split(" ");
        answer = Integer.valueOf(sArr[0]);
        
        for(int i = 1; i < sArr.length; i+=2) {
            if (sArr[i].equals("+")) {
                answer += Integer.valueOf(sArr[i+1]);
            } else {
                answer -= Integer.valueOf(sArr[i+1]);
            }
        }        
        return answer;
    }
}