프로그래머스 코딩테스트(제곱수 판별하기, 특정한 문자를 대문자로 바꾸기, 홀짝 구분하기)
<제곱수 판별하기>
import java.lang.Math;
class Solution {
public int solution(int n) {
int answer = 0;
return Math.sqrt(n)==(double)((int)Math.sqrt(n))?1:2;
}
}
다른 사람 풀이
class Solution {
public int solution(int n) {
int answer = 0;
return Math.sqrt(n) % 1 == 0 ? 1 : 2;
}
}
class Solution {
public int solution(int n) {
if (n % Math.sqrt(n) == 0) {
return 1;
} else {
return 2;
}
}
}
<특정한 문자를 대문자로 바꾸기>
문제 설명
영소문자로 이루어진 문자열 my_string과 영소문자 1글자로 이루어진 문자열 alp가 매개변수로 주어질 때, my_string에서 alp에 해당하는 모든 글자를 대문자로 바꾼 문자열을 return 하는 solution 함수를 작성해 주세요.
풀이
class Solution {
public String solution(String my_string, String alp) {
String answer = "";
for(int i=0;i<my_string.length();i++){
if(alp.equals(my_string.charAt(i)+"")){
answer+=(my_string.charAt(i)+"").toUpperCase();
} else
answer+=my_string.charAt(i);
}
return answer;
}
}
<홀짝 구분하기>
문제 설명
자연수 n이 입력으로 주어졌을 때 만약 n이 짝수이면 "n is even"을, 홀수이면 "n is odd."를 출력하는 코드를 작성해 보세요.
풀이
import java.util.Scanner;
public class Solution {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
if(n%2==0){
System.out.println(n+" is even");
} else
System.out.println(n+" is odd");
}
}