기본 콘텐츠로 건너뛰기

프로그래머스 - 시저 암호

public class Caesar {
    String caesar(String s, int n) {
    n%=26;
        String result = "";
        char[] temp = s.toCharArray();
        for(int i=0;i<temp.length;i++) {
            if(temp[i]>='a' &&temp[i]<='z')
                temp[i] = (char) ((temp[i]+n)>'z' ? (temp[i]+n-1)%'z'+'a' : (temp[i]+n));  
            else if(temp[i]>='A' &&temp[i]<='Z')
                temp[i] = (char) ((temp[i]+n)>'Z' ? (temp[i]+n-1)%'Z'+'A' : (temp[i]+n));
            result+=temp[i];
        }

        return result;
    }

    public static void main(String[] args) {
        Caesar c = new Caesar();
        System.out.println("s는 'a B z', n은 4인 경우: " + c.caesar("a B z", 4));
    }
}
알파벳의 대소문자를 조건문의 범위로 확인하는 방법 말고 Character.isLowerCase()가 있음
삼항 연산자를 사용한 라인에서
temp[i] = (char) ((temp[i] - 'a' + n) % 26 + 'a'); 
로 하면 분기를 줄일 수 있음

댓글

이 블로그의 인기 게시물

프로그래머스 - 나누어 떨어지는 숫자 배열

import java.util.Arrays ; public class Divisible { public int [] divisible( int [] array, int divisor) { int [] temp = new int [array.length]; int idx = 0 ; for ( int i= 0 ;i<array.length;i++) { if (array[i]%divisor== 0 ) { temp[idx++] = array[i]; } } int [] ret = new int [idx]; for ( int i= 0 ;i<idx;i++) { ret[i] = temp[i]; } return ret; } // 아래는 테스트로 출력해 보기 위한 코드입니다. public static void main( String [] args) { Divisible div = new Divisible(); int [] array = { 5 , 9 , 7 , 10 }; System .out.println( Arrays .toString( div.divisible(array, 5 ) )); } } 아래의 풀이도 있는데 간결해서 깜짝놀라고 속도 떨어지는 것에 또 놀랐다. import java.util.Arrays ; class Divisible { public int [] divisible( int [] array, int divisor) { return Arrays .stream(array).filter(factor -> factor % divisor == 0 ).toArray...