본문 바로가기

코딩테스트/Coding Bat

[코딩뱃] [자바] Warmup - 1단계 : front3 문제

728x90
728x90

https://codingbat.com/prob/p136351

 

CodingBat Java Warmup-1 front3

Given a string, we'll say that the front is the first 3 chars of the string. If the string length is less than 3, the front is whatever is there. Return a new string which is 3 copies of the front.

codingbat.com



= 문제 번역 =

문자열이 주어지면 주어진 문자열의 처음 3글자를 가져옵니다. 그 후, 3글자를 3번 반복한 문자열을 반환합니다.

만약, 문자열 길이가 3보다 작을 때는, 그 작은 문자열을 3번 반복합니다.

 

= 문제푸는 팁 =

해설 2번이, 코딩뱃에서 준 솔루션인데, 나같은 경우는 미지수 n으로 만들어서, return값을 다르게 주었다

하지만 코딩뱃 사이트에선 front를 return값 하나로 주고, if 안에서 front변수의 값을 다르게 저장했다.

나도 앞으로 저런식으로 문제를 풀어야지!

 

= 해설 =

< 1 >
public String front3(String str) {
  if(str.length()>=3){
    n=str.substring(0,3);
    return n+n+n;
  }else return str+str+str;
}

<2>
public String front3(String str) {
  String front;
  
  if (str.length() >= 3) {
    front = str.substring(0, 3);
  }
  else {
    front = str;
  }
  return front + front + front;
}

 

728x90