티스토리 뷰
문제 설명
단어 s의 가운데 글자를 반환하는 함수, solution을 만들어 보세요. 단어의 길이가 짝수라면 가운데 두글자를 반환하면 됩니다.
재한사항
- s는 길이가 1 이상, 100이하인 스트링입니다.
입출력 예
s | return |
---|---|
abcde |
c |
qwer |
we |
Solution 1 in Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
class Solution {
public String solution(String s) {
String answer = "";
int position = 0;
int length = 0;
if (s.length() % 2 == 0){
position = s.length() / 2 - 1;
length = 2;
}else if(s.length() % 2 == 1){
position = s.length() / 2;
length = 1;
}
answer = s.substring(position, position + length);
return answer;
}
}
|
cs |
substring() method is (include,exclude)
Solution 2 in Java
1
2
3
4
5
6
7
8
9
10
11
12
|
class Solution {
public String solution(String s) {
String answer = "";
int half = s.length()/2;
if(s.length() % 2 == 1){ //odd
answer = s.substring(half,half + 1);
}else if(s.length() % 2 == 0){ //even
answer = s.substring(half - 1,half + 1);
}
return answer;
}
}
|
cs |
Solution 3 in JavaScript
function Solution(prop) {
const middle = prop.length / 2;
// @ts-ignore
const first = Math.trunc(middle) + 1;
const second = first - 2;
for(let i = 0; i < prop.length; i++) {
if(prop.length % 2 === 0){
return (prop.slice(second, first))
} else {
return (prop[first-1]);
}
}
}
console.log(Solution("abc"));
Solution 4 in JavaScript
function solution(s) {
if(s.length%2 == 0){
return s.substr(s.length/2-1,2)
}else{
return s.substr(s.length/2,1)
}
}
function solution2(s) {
return s.substr(Math.ceil(s.length / 2) - 1, s.length % 2 === 0 ? 2 : 1);
}
console.log(solution('123456'));
console.log(solution2('123'));
reference
https://programmers.co.kr
'Algorithms' 카테고리의 다른 글
<프로그래머스 알고리즘문제> 문자열 다루기 기본 (0) | 2019.01.21 |
---|---|
<프로그래머스 알고리즘문제> 약수의 합 (0) | 2019.01.18 |
<프로그래머스 알고리즘문제> 서울에서 김서방 찾기 (0) | 2019.01.17 |
<프로그래머스 알고리즘문제> Convert String to int (0) | 2019.01.15 |
<프로그래머스 알고리즘문제> 수박수박수? (0) | 2019.01.15 |
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
링크
TAG
- hackerrank javascript
- easy javascript algorithm
- Object type casting
- algorithm
- hackerrank
- easy algorithm
- ... in Javascript
- 프로그래머스
- spring boot application
- Collection Framework
- math.max
- math.abs
- 알고리즘
- 프로그래머스 알고리즘
- string class in java
- javascript
- code refactoring
- C++
- hackerrank javascript solution
- substring()
- java
- 프로그래머스 알고리즘문제
- Javascript Algorithm
- equals()
- HackerRank Algorithm
- HashMap
- repeat()
- hackerrank solution
- rest parameter
- compareTo()
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 |
글 보관함