카테고리 없음

2주 2일차 알고리즘 문제풀이(개인)

Zpoxic 2021. 11. 9. 09:07

1. 수박수박수박수박수?

[기본 상태]

class Solution {
public String solution(int n) {
String answer = "";
return answer;
}
}

[풀이에 필요한 조건]

String answer에 + 연산자를 통해 붙여줄 "수", "박"의 String 선언.

 

입력받는 값만큼 반복을 돌려줄 for문 작성. ( 루프 시작 i=1, 끝 i<=n)

 

if문을 통해 짝수가 아니라면( i%2 != 0) answer에 "수" String을 추가해줌.

 

짝수라면 "박" String을 추가해줌.

[해답]

class Solution {
public String solution(int n) {
String answer = "";
String text1 = "";
String text2 = "";

for(int i=1;i<=n;i++){
if(i%2!=0){
answer += text1;
}
else{
answer += text2;
}
}
return answer;
}
}

더보기
class Solution {
public String solution(int n) {
String answer = "";
String text1 = "";
String text2 = "";

for(int i=1;i<=n;i++){
if(i%2!=0){
answer += text1;
}
else{
answer += text2;
}
}
return answer;
}
}

public class Main {
public static void main(String[] args) {
Solution sol = new Solution();

int n1 = 3;
int n2 = 4;

String result1 = sol.solution(n1);
String result2 = sol.solution(n2);

System.out.println(result1);
System.out.println(result2);
}
}

 

 

2. 자연수 뒤집기

[기본 상태]

class Solution {
    public int[] solution(long n) {
        int[] answer = {};
        return answer;
    }
}

[풀이에 필요한 조건]

배열의 길이를 정하기 위해 지급받는 값 n의 자릿수를 구해줘야함.

long 형태의 자료를 int로 강제 변환하여 log 계산을 통해 제곱수를 구하고 +1을 더해 자리수를 계산해줌.

Math.log10(n)+1

ex) Math.log10(1000) = 3, 1천의 자리까지 1자리 추가

 

배열 입력과 제곱식을 구하기위해 for문 작성.

 

Math.pow(a, b) (a의  b승) 을 사용하기 위해 data가 double 형태가 되어야함.

double 형태로 계산값을 받기 위해 insert_n을 선언하고,

double 형태로 변환한 n을 이용하여 나머지 계산 후 나누기 계산을 통해 ( i+1)번째 자리값의 데이터를 남김.

 

int 형태로 변환한 insert_n 값을 배열에 추가.

 

i = 0, 12345 % 10 = 5 /1 = 5
i = 1, 12345 % 100 = 45 /10 = 4.5
i = 2, 12345 % 1000 = 345 /100 = 3.45
i = 3, 12345 % 10000 = 2345 /1000 = 2.345
i = 4, 12345 % 100000 = 12345 /10000 = 1.2345
나머지 계산 Math.pow(10,i+1)
나누기 계산 Math.pow(10,i)

[해답]

class Solution {
public int[] solution(long n) {
int n_length = (int)(Math.log10(n)+1);
int[] answer = new int[n_length];

for(int i=0 ; i<n_length ; i++){
double insert_n = (double)n%Math.pow(10,i+1)/Math.pow(10,i);
answer[i]=(int)insert_n;
}
return answer;
}
}

더보기
class Solution {
public int[] solution(long n) {
int n_length = (int)(Math.log10(n)+1);
int[] answer = new int[n_length];

for(int i=0 ; i<n_length ; i++){
//i = 0, 12345 % 10 = 5 /1 = 5
//i = 1, 12345 % 100 = 45 /10 = 4
//i = 2, 12345 % 1000 = 345 /100 = 3
//i = 3, 12345 % 10000 = 2345 /1000 = 2
//i = 4, 12345 % 100000 = 12345 /10000 = 1
//System.out.println(Math.pow(10,i+1));
//System.out.println(Math.pow(10,i));

double insert_n = (double)n%Math.pow(10,i+1)/Math.pow(10,i);

answer[i]=(int)insert_n;
}
return answer;
}
}

public class Main {
public static void main(String[] args) {
Solution sol = new Solution();

long n1 = 12345;

int[] result1 = sol.solution(n1);

System.out.print("{");
for(int i=0 ; i<(int)(Math.log10(n1)+1) ; i++ ){
if(i==(int)(Math.log10(n1))){
System.out.print(result1[i]);
}
else{
System.out.print(result1[i] + " , ");
}
}
System.out.print("} \n");
}
}
더보기

//reverse()로 뒤집어서 String으로 저장하고, answer에 순서대로 넣어주는 방법.

class Solution {
public int[] solution(long n) {
String s = String.valueOf(n);
StringBuilder sb = new StringBuilder(s);
sb = sb.reverse();
String[] ss = sb.toString().split("");

int[] answer = new int[ss.length];
for (int i=0; i<ss.length; i++) {
answer[i] = Integer.parseInt(ss[i]);
}
return answer;
}
}

3. 콜라스 추측

[기본 상태]

class Solution {
    public int solution(int num) {
        int answer = 0;
        return answer;
    }
}

[풀이에 필요한 조건]

연산하는 결과값이 1일 때, 루프를 탈출하기위해 for문 위에 loop: 를 씌워 조건에 맞는 경우 루프를 탈출하도록 함. (break loop;)

 

연산이 1회 진행될 때마다 answer 을 +1 해줌.

 

총 계산 횟수가 500회가 되면 answer에 -1을 넣고 반복을 종료하여 값을 return 함.

 

연산에 사용되는 변수가 int이면 안 됨. 

int 형태에서 표현 가능한 최대 정수는 2,147,483,647 이기 때문.

https://ko.wikipedia.org/wiki/2147483647

[해답]

class Solution {
public int solution(int num) {
int answer = 0;
// 3번 예제의 숫자는 int형으로 계산시에 int형 자료의 최댓값인 2,147,483,647 을 넘게되어 연산이 정상적으로 수행되지 않음
// long형의 변수로 대체하여 계산
long long_num=num;

loop:
for(int i=1 ; i<=500 ; i++){
if(long_num==1){
break loop;
}
else if(long_num%2 == 0){
long_num /= 2;
answer += 1;
}
else{
long_num = long_num*3+1;
answer += 1;
}
if(i==500){
answer = -1;
}
}
return answer;
}
}

더보기
class Solution {
public int solution(int num) {
int answer = 0;
// 3번 예제의 숫자는 int형으로 계산시에 int형 자료의 최댓값인 2,147,483,647 을 넘게되어 연산이 정상적으로 수행되지 않음
// long형의 변수로 대체하여 계산
long long_num=num;

loop:
for(int i=1 ; i<=500 ; i++){
if(long_num==1){
break loop;
}
else if(long_num%2 == 0){
long_num /= 2;
answer += 1;
}
else{
long_num = long_num*3+1;
answer += 1;
}
if(i==500){
answer = -1;
}
}
return answer;
}
}

public class Main {
public static void main(String[] args) {
Solution sol = new Solution();

int num1=6;
int num2=16;
int num3=626331;

int result1 = sol.solution(num1);
int result2 = sol.solution(num2);
int result3 = sol.solution(num3);

System.out.println(result1);
System.out.println(result2);
System.out.println(result3);
}
}