본문 바로가기

코딩테스트/Coding Bat

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

728x90
728x90

https://codingbat.com/prob/p183592

 

CodingBat Java Warmup-1 front22

Given a string, take the first 2 chars and return the string with the 2 chars added at both the front and back, so "kitten" yields"kikittenki". If the string length is less than 2, use whatever chars are there.

codingbat.com



= 문제 번역 =

문자열이 주어지면 처음 2개의 문자를 가져옵니다.

앞 뒤 모두에 2개의 문자가 추가된 문자열을 반환하므로, "kitten"은 "kikittenki"를 산출합니다. 

문자열 길이가 2보다 작으면 거기에 있는 모든 문자를 사용하십시오.

 

= 문제푸는 팁 =

warmup - 1단계의 front3문제와 비슷한 문제로, 3번 반복이 아닌, 앞 뒤에 문자열이 붙는 문제로

문제의 조건을 잘 확인하고 푼다면 어렵지는 않은 문제이다. 

2번 해설같은경우엔 코딩뱃 해설인데, 굳이 str.length가 2보다 크지않다를 쓰는것보다 take를 변수로 사용해서 

풀이를 했는데, 어느게 프로그래밍에서 더 나은 해설인지 아직은 잘 모르겠다.

 

= 해설 =

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

< 2 >
public String front22(String str) {
  // First figure the number of chars to take
  int take = 2;
  if (take > str.length()) {
    take = str.length();
  }
  
  String front = str.substring(0, take);
  return front + str + front;
}

728x90