프로그래머스 코딩테스트(암호 해독, 더 크게 합치기, 가위 바위 보)
<암호 해독>
문제 설명
군 전략가 머쓱이는 전쟁 중 적군이 다음과 같은 암호 체계를 사용한다는 것을 알아냈습니다.
암호화된 문자열 cipher를 주고받습니다.
그 문자열에서 code의 배수 번째 글자만 진짜 암호입니다.
문자열 cipher와 정수 code가 매개변수로 주어질 때 해독된 암호 문자열을 return하도록 solution 함수를 완성해주세요.
풀이
class Solution {
public String solution(String cipher, int code) {
String answer = "";
for(int i=0;i<cipher.length();i++){
if((i+1)%code==0)
answer+=cipher.charAt(i);
}
return answer;
}
}
다른 사람 풀이
class Solution {
public String solution(String cipher, int code) {
String answer = "";
for (int i = code; i <= cipher.length(); i = i + code) {
answer += cipher.substring(i - 1, i);
}
return answer;
}
}
<더 크게 합치기>
문제 설명
연산 ⊕는 두 정수에 대한 연산으로 두 정수를 붙여서 쓴 값을 반환합니다. 예를 들면 다음과 같습니다.
12 ⊕ 3 = 123
3 ⊕ 12 = 312
양의 정수 a와 b가 주어졌을 때, a ⊕ b와 b ⊕ a 중 더 큰 값을 return 하는 solution 함수를 완성해 주세요.
단, a ⊕ b와 b ⊕ a가 같다면 a ⊕ b를 return 합니다.
풀이
class Solution {
public int solution(int a, int b) {
return Integer.parseInt(""+a+b)>=Integer.parseInt(""+b+a)?Integer.parseInt(""+a+b):Integer.parseInt(""+b+a);
}
}
다른 사람 풀이
class Solution {
public int solution(int a, int b) {
String strA = String.valueOf(a);
String strB = String.valueOf(b);
String strSum1 = strA + strB;
String strSum2 = strB + strA;
return Math.max(Integer.valueOf(strSum1), Integer.valueOf(strSum2));
}
}
<가위 바위 보>
문제 설명
가위는 2 바위는 0 보는 5로 표현합니다. 가위 바위 보를 내는 순서대로 나타낸 문자열 rsp가 매개변수로 주어질 때, rsp에 저장된 가위 바위 보를 모두 이기는 경우를 순서대로 나타낸 문자열을 return하도록 solution 함수를 완성해보세요.
풀이
class Solution {
public String solution(String rsp) {
String answer = "";
for(int i=0;i<rsp.length();i++){
switch(rsp.charAt(i)){
case '2':
answer+="0";
break;
case '0':
answer+="5";
break;
default:
answer+="2";
}
}
return answer;
}
}