연산

2dean·2023년 5월 21일
0

java 기초

목록 보기
3/3
post-thumbnail

문제 1 - 문자 리스트를 문자열로 변환

문자들이 담겨있는 배열 arr가 주어집니다. arr의 원소들을 순서대로 이어 붙인 문자열을 return 하는 solution함수를 작성해 주세요.

예시

입출력 예

arrresult
["a","b","c"]"abc"

풀이

static String solution(String[] arr) {
	String result= "";
    for (String item : arr) {
        result += item;
    }
      return result;
}
static String solution(String[] arr) {
	StringBuilder sb = new StringBuilder();
        for(String item : arr) {
            sb.append(item);
        }
    return sb.toString();
}

문제 2 - 문자열 곱하기

문자열 my_string과 정수 k가 주어질 때, my_string을 k번 반복한 문자열을 return 하는 solution 함수를 작성해 주세요.

입출력예

my_stringkresult
"string"3"stringstringstring"
"love"10"lovelovelovelovelovelovelovelovelovelove"

풀이

class Solution {
    public String solution(String my_string, int k) {  
        StringBuilder sb = new StringBuilder();
        for(int i= 0; i < k; i++) {
            sb.append(my_string);
        }
        return sb.toString();
    }
}

문제 3 - 더 크게 합치기

연산 ⊕는 두 정수에 대한 연산으로 두 정수를 붙여서 쓴 값을 반환합니다. 예를 들면 다음과 같습니다.

12 ⊕ 3 = 123
3 ⊕ 12 = 312
양의 정수 a와 b가 주어졌을 때, a ⊕ b와 2 a b 중 더 큰 값을 return하는 solution 함수를 완성해 주세요.

단, a ⊕ b와 2 a b가 같으면 a ⊕ b를 return 합니다.

풀이

static int solution(int a, int b) {
  String aString = Integer.toString(a);
  String bString = Integer.toString(b);  
  int ab = Integer.parseInt(aString + bString);
  int ba = Integer.parseInt(bString + aString);
  if (ab > ba) {
  	return ab;
  } else {
  	return ba;
  }
}
  • String 으로 바꾸는 다른 방법
  String key1 = "" + a + b;
  String key2 = "" + b + a;
  • 또 다른방법
 String key1 = String.valueOf(a);
 String key2 = String.valueOf(b);

문제 4 - 두 수의 연산값 비교하기

연산 ⊕는 두 정수에 대한 연산으로 두 정수를 붙여서 쓴 값을 반환합니다. 예를 들면 다음과 같습니다.

12 ⊕ 3 = 123
3 ⊕ 12 = 312
양의 정수 a와 b가 주어졌을 때, a ⊕ b와 2 a b 중 더 큰 값을 return하는 solution 함수를 완성해 주세요.

단, a ⊕ b와 2 a b가 같으면 a ⊕ b를 return 합니다.

풀이

class Solution {
    public int solution(int a, int b) {
        String aString = "" + a;
        String bString = "" + b;
        int plus = Integer.parseInt(aString + bString);
        int multiply = 2 * a* b;
        if (plus > multiply || plus == multiply) {
            return plus;
        } else { 
            return multiply;
        }
    }
}
  • 더 간결하고 좋아보임
class Solution {
    public int solution(int a, int b) {
        int ab = Integer.parseInt(a + "" + b);
        if(2 * a * b <= ab) {
            return ab;
        } else {
            return 2 * a * b;
        }
    }
}
profile
냅다 써보는 공부의 흔적😇

0개의 댓글