프로그래머스8일차

지선·2023년 5월 4일

코딩테스트

목록 보기
8/8

잘라서 배열로 저장하기

class Solution {
    public String[] solution(String my_str, int n) {
        int len=my_str.length()/n;
        if (my_str.length()%n!=0) {
            len++;
        }
        String[] answer=new String[len];
        
        int cnt=0;
        for (int i=0;i<len;i++) {
            answer[i]="";
            int start=i*n;
            int end=(i+1)*n;
            if (end>my_str.length()) {
                end=my_str.length();
            }
            answer[i]+=my_str.substring(start, end);
            cnt++;
            if (cnt==n) {
                cnt=0;
            }
        }
        return answer;
    }
}

숨어있는 숫자의 덧셈(1)

class Solution {
    public int solution(String my_string) {
        int answer = 0;
        my_string=my_string.replaceAll("[^0-9]","");
        for(int i=0;i<my_string.length();i++){
           answer+=Integer.parseInt(String.valueOf(my_string.charAt(i)));
        }
        return answer;
    }
}

모스부호

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

dictionary를 처음 사용해봤는데 신기했다. 파이썬이랑 비슷한듯 !!

팩토리얼

class Solution {
    public int solution(int n) {
        int answer=0;
        int a=1, cnt=0;
        
        while(true){
            cnt++;
            a=a*cnt;
            if(a==n){
                return answer=cnt;
            }
            else if(a>n){
                break;
            }
        }
        return answer=cnt-1;
    }
}

자꾸 한 번씩.. 틀리고.. ㅠ
계속 다시 풀어봐야한다..

내일은 여행을 가서 3일간은 TIL을 못할 것 같다. 돌아와서 다시 화이팅하자 !!

profile
긍정왕되기

0개의 댓글