매일 Algorithm

신재원·2024년 1월 10일
0

Algorithm

목록 보기
242/243

코딩테스트 입문 369게임

매우 간단한 문제였다.
1. 매개변수인 order를 String 객체로 변환하여 3,6,9를 포함하는지 확인하여 answer 변수를 증가 시켜주면 된다.

class Solution {
    public int solution(int order) {
        int answer = 0;
        
        String number = String.valueOf(order);
        String[] numbers = number.split("");
        
        for(String findNumber : numbers){
            if(findNumber.equals("3") ||
               findNumber.equals("6") ||
               findNumber.equals("9")){
                answer++;
            }
        }
        return answer;
    }
}

코딩테스트 입문 다항식 더하기

조건문을 작성하는게 조금 어려웠던 문제였다.

  1. 주어진 매개변수에서 x항상수항을 따로 변수에 저장합니다.
  2. 따로 저장한 변수를 비교합니다.
    • x항만 값이 존재할 경우
    • 상수항만 값이 존재할 경우
    • x항과 상수항 둘다 값이 존재할 경우
class Solution {
    public String solution(String polynomial) {
        String answer = "";
        String [] words = polynomial.split(" +");
        
        int total1 = 0; // x항 총합
        int total2 = 0; // 상수항 총합
        
        // 3x, 7, x
        
        // 1. 입력값에 대한 x항과 상수항 계산
        for(String word : words){
            if(word.equals("x")){
                total1 += 1;
            }else if(word.contains("x")){
                total1 += Integer.parseInt(word.substring(0, word.length() - 1));
            }else if(!word.equals("+")){
                total2 += Integer.parseInt(word);
            }
        }
        
        // 2. x항만 값이 존재할 경우
        if(total1 != 0 && total2 == 0){
            if(total1 == 1){
                answer = "x";
            }else{
                answer = total1 + "x";
            }
        }
        
        // 3. 상수항만 값이 존재할 경우
        if(total1 == 0 && total2 != 0){
            answer = String.valueOf(total2);
        }
              
        // 4. x항과 상수항 둘다 값이 존재할 경우
        if(total1 != 0 && total2 != 0){
            if(total1 == 1){
                answer = "x" + " + " + total2;
            }else{
                answer = total1 + "x" + " + " + total2;
            }
        }
        
        return answer;
    }
}

코딩테스트 입문 겹치는 선분의 길이

  1. 겹치는 선분이라는 정의를 잘 파악해야함
  2. Map 객체를 선언하여 선분의 길이만큼 value값을 저장한다.
  3. value 값이 2 이상인 경우는 겹치는 선분이 있다는 것이다.
import java.util.Map;
import java.util.HashMap;

class Solution {
    public int solution(int[][] lines) {
        int answer = 0;
        Map<Integer, Integer> store = new HashMap<>();

        // 1. store 객체 초기화
        for(int i = -100; i <= 100; i++){
            store.put(i, 0);
        }
        
        for(int i = 0; i < lines.length; i++){
            // 2. 시작 선분부터 끝 선분까지 반복
            for(int j = lines[i][0]; j < lines[i][1]; j++){
                store.put(j, store.get(j) + 1);
            }
        }

        // 3. store 객체의 value 값이 2인 경우는 겹치는 선분이 있다는것
        for(int findNumber : store.values()){
            if(findNumber >= 2){
                answer++;
            }
        }
        return answer;
    }
}

0개의 댓글