본문 바로가기

Algorithm

자바 알고리즘 연습(7)

가운데 글자 가져오기

  • String을 char배열로 : 변수명.charAt(index접근 가능);
class Solution {
    public String solution(String s) {
        String answer = "";
        if (s.length() % 2 == 0){
            answer += s.charAt(s.length() / 2 - 1);
            answer += s.charAt(s.length() / 2);
        } else {
            answer += s.charAt(s.length() / 2);
        }
        return answer;
    }
}

 

수박수박수박수박수박수?

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

 

내적

class Solution {
    public int solution(int[] a, int[] b) {
        int answer = 0;
        for(int i = 0; i < a.length; i++){
            answer = answer + a[i] * b[i];
        }
        return answer;
    }
}

 

약수의 개수와 덧셈

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

 

문자열 내림차순으로 배치하기

import java.util.*;
class Solution {
    public String solution(String s) {
        char[] sArr = s.toCharArray();
        Arrays.sort(sArr);
        StringBuilder answer = new StringBuilder();
        for (int i = sArr.length-1; i >= 0; i--){
            answer.append(sArr[i]);
        }
        return answer.toString();
    }
}