[프로그래머스]시저 암호

mongs_Develop·2022년 5월 6일
0

Programmers-Level1-Java

목록 보기
17/30
post-thumbnail
  • 문제 & 예시

  • 소스코드

import java.nio.charset.StandardCharsets;

// 시저 암호
public class test17 {
	public static void main(String[] args) {
		Solution17 sol = new Solution17();
		String s = "a B z";
		int n = 4;
		System.out.println(sol.solution(s, n));
	}
}
class Solution17 {
    public String solution(String s, int n) {
        String answer = "";
        // 문자열 s의 대한 10진 아스키코드 값으로 변환하여 bytes 배열에 대입
        byte[] bytes = s.getBytes(StandardCharsets.US_ASCII);
       
        for(int i=0;i<s.length();i++) {
        	// 대문자일 경우
        	if(bytes[i]>=65 && bytes[i]<=90) { 
        		bytes[i] = (byte) ((bytes[i] + n - 65) % 26 + 65);
        	}
        	// 소문자일 경우
        	else if(bytes[i]>=97 && bytes[i]<=122) { 
        		bytes[i] = (byte) ((bytes[i] + n - 97) % 26 + 97);
        	}       		
        	// 공백일 경우
        	if(bytes[i] - n == 32) {
        		bytes[i] = 32;
        	}
        	// 문자열 answer에 bytes배열값인 10진 아스키코드 값을 -> 문자열로 변환하여 저장
        	answer += Character.toString(bytes[i]);       	
        } 
        return answer;
    }
}
  • consol
profile
개 발 인생

0개의 댓글