본문 바로가기

study_IT/알고리즘 노트

[programmers] 코딩테스트 입문 Day 9

728x90
반응형

1. 개미군단

class Solution {
    public int solution(int hp) {
        int answer = 0;
        
        answer += hp / 5;
        
        answer += (hp % 5) / 3;
        
        answer += ((hp % 5) % 3 ) / 1;
        
              
        return answer;
    }
}

2. 모스부호(1)

import java.util.Map;
import java.util.HashMap;

class Solution {
    public String solution(String letter) {
        String answer = "";
        
        Map<String, String> morse = new HashMap<>();
        morse.put(".-","a"); morse.put("-...","b");morse.put("-.-.","c");
        morse.put("-..","d"); morse.put(".","e");morse.put("..-.","f");morse.put("--.","g");
        morse.put("....","h");morse.put("..","i");morse.put(".---","j");morse.put("-.-","k");
        morse.put(".-..","l");morse.put("--","m");morse.put("-.","n");morse.put("---","o");
        morse.put(".--.","p");morse.put("--.-","q");morse.put(".-.","r");morse.put("...","s");
        morse.put("-","t");morse.put("..-","u");morse.put("...-","v");morse.put(".--","w");
        morse.put("-..-","x");morse.put("-.--","y");morse.put("--..","z");
        
        
        String result[] = letter.split(" ");
        
        for (int i=0; i<result.length; i++){
          for(String key : morse.keySet()){
              if(result[i].equals(key))
              {
                  answer += morse.get(key);
              } 
          }
             
          }
        
        
       return answer;
    }
}

3. 가위 바위 보

class Solution {
    public String solution(String rsp) {
        String answer = "";
        
        for(int i=0; i<rsp.length(); i++){
            
            if(rsp.charAt(i) == '2'){
                answer+= "0";
            } else if(rsp.charAt(i) == '0'){
                answer+= "5";
            } else if(rsp.charAt(i) == '5'){
                 answer+= "2";
            }
            
        }
        
        
        return answer;
    }
}

4. 구슬을 나누는 경우의 수

import java.math.BigInteger;

class Solution {
    public BigInteger solution(int balls, int share) {
        if (balls < share) {
            return BigInteger.ZERO; // Invalid input, cannot select more balls than available
        }

        BigInteger numerator = BigInteger.ONE;
        BigInteger denominator = BigInteger.ONE;

        // Calculate numerator (balls!)
        for (int i = 1; i <= balls; i++) {
            numerator = numerator.multiply(BigInteger.valueOf(i));
        }

        // Calculate denominator (share! * (balls - share)!)
        for (int i = 1; i <= share; i++) {
            denominator = denominator.multiply(BigInteger.valueOf(i));
        }
        for (int i = 1; i <= balls - share; i++) {
            denominator = denominator.multiply(BigInteger.valueOf(i));
        }

        // Calculate combination (numerator / denominator)
        BigInteger answer = numerator.divide(denominator);

        return answer;
    }
}
728x90
반응형