► JS Algorithm/Programmers
[Programmers] JavaScript 알고리즘 | Lv.0 k의 개수
다람트리
2024. 7. 8. 23:45
반응형
🔒 문제 설명
1부터 13까지의 수에서, 1은 1, 10, 11, 12, 13 이렇게 총 6번 등장합니다. 정수 i, j, k가 매개변수로 주어질 때, i부터 j까지 k가 몇 번 등장하는지 return 하도록 solution 함수를 완성해주세요.
🔒 제한사항
- 1 ≤ i < j ≤ 100,000
- 0 ≤ k ≤ 9
🔒 입출력 예
i | j | k | result |
1 | 13 | 1 | 6 |
10 | 50 | 5 | 5 |
3 | 10 | 2 | 0 |
🔒 입출력 예 설명
입출력 예 #1
- 본문과 동일합니다.
입출력 예 #2
- 10부터 50까지 5는 15, 25, 35, 45, 50 총 5번 등장합니다. 따라서 5를 return 합니다.
입출력 예 #3
- 3부터 10까지 2는 한 번도 등장하지 않으므로 0을 return 합니다.
🔐 solution of mine
Array.prototype.filter()
function solution(i, j, k) {
let txt = "";
for (i; i <= j; i++) {
txt += String(i);
}
return console.log([...txt].filter((v) => v === String(k)).length);
}
solution(1, 13, 1); //output: 6
solution(10, 50, 5); //output: 5
solution(3, 10, 2); //output: 0
🔐 solution of others
String.prototype.split()
function solution(i, j, k) {
let a = "";
for (i; i <= j; i++) {
a += i;
}
return console.log(a.split(k).length - 1);
}
solution(1, 13, 1); //output: 6
solution(10, 50, 5); //output: 5
solution(3, 10, 2); //output: 0
split() 메서드는 String 객체를 지정한 구분자를 이용하여 여러 개의 문자열로 나눕니다.
🔐 solution of others
Array() 생성자
Array.prototype.fill()
Array.prototype.map()
Array.prototype.join()
Array.from()
Array.prototype.filter()
단항 더하기 (+)
function solution(i, j, k) {
const str = Array(j - i + 1)
.fill(i)
.map((v, i) => v + i)
.join("");
return console.log(Array.from(str).filter((v) => +v === k).length);
}
solution(1, 13, 1); //output: 6
solution(10, 50, 5); //output: 5
solution(3, 10, 2); //output: 0
단항 더하기 연산자(+)는 피연산자 앞에 위치하며 피연산자를 평가하지만, 만약 피연산자가 숫자가 아니라면 숫자로 변환을 시도합니다.
반응형