지영이의 개발 블로그

✔[프로그래머스]덜 푼 문제풀기 -5문제 (1) 본문

코딩/코딩테스트

✔[프로그래머스]덜 푼 문제풀기 -5문제 (1)

이지영 2022. 7. 18. 12:32

1. 자릿수 더하기

<My solution>

👉string 함수로 문자열을 배열로 만들어준후 reduce 함수를 써 누적 합을 더해준다

paseint 함수는 문자열이 숫자로 시작한다면 숫자만을 리턴

2.이상한 문자 만들기

<My solution>

👉map()을 이용해서 배열 순회 후 새로운 배열로 return 배열의 index가 짝수이면 toUpperCase 함수사용 홀수인 경우 toLowCase 함수 사용

3.정수 내림차순으로 배치하기

<My solution>

4.정수 제곱근 판별

<My solution>

👉Math.sqrt는 제곱근을 반환한다 제곱근의 값이 양의정수라면 x+1의 제곱을 리턴하고 아니라면 -1을 반환한다

5.제일 작은수 제거하기

<indexOf>

인자로 받은 값을 찾아 맞는 식별자 반환

  • arr.indexOf(search, fromIndex)
  • 반환 타입 number, 없다면 -1
  • search 매개변수는 배열에서 찾을 요소를 받음
  • 원하는 요소의 식별자 찾기
  • 원하는 요소를 찾자마자 메서드를 종료함
const arr = [5, 6, 9, 1, 6, 3, 2, 1, 2, 7, 9, 4, 3];

const find1 = arr.indexOf(1);
const find2 = arr.indexOf(2);
const find3 = arr.indexOf(3);
const find4 = arr.indexOf(4);

console.log('findIndex1:', find1);
console.log('findIndex2:', find2);
console.log('findIndex3:', find3);
console.log('findIndex4:', find4);
findIndex1: 3
findIndex2: 6
findIndex3: 5
findIndex4: 11

Math.min(), Math.max() : 배열에서 최대, 최소 값 찾기

min(num1, num2, ....), max(num1, num2, ....)는 인자로 전달된 숫자 중에 최소, 최대 값을 찾아서 리턴합니다. 인자 개수는 제한이 없습니다.

const min = Math.min(10, 20, 30, 40);
const max = Math.max(10, 20, 30, 40);

console.log(min);  // 10
console.log(max);  // 40

이 함수들을 이용하여 배열의 모든 요소를 min(), max()에 전달하면 배열의 최대, 최소 값을 찾을 수 있습니다. 특히, Spread Operator(전개 연산자)를 이용하면 배열의 모든 요소를 쉽게 함수의 인자로 전달할 수 있습니다. Spread Operator는 ...arr와 같은 표현식이며, 배열 arr의 모든 요소를 나열하여 인자로 전달합니다.

아래 예제는 min(), max()와 Spread Operator를 이용하여 최대, 최소값을 찾는 예제입니다.

const arr = [30, 40, 10, 20];

const min = Math.min(...arr);
const max = Math.max(...arr);

console.log(min);
console.log(max);
10
40

<My solution>

👉만약 값이 하나이상 이면 배열에서 가장 작은 요소를 찾고, 그것의 인덱스로 찾아서 하나 제거한다.

배열의 길이가 0 or 1 일 경우 -1 반환.\\

<Other solution>

Math.min.apply(), Math.max.apply() : 배열에서 최대, 최소 값 찾기

Math.min.apply(null, array)는 인자로 전달한 array 배열 요소들 중에 최소 값을 리턴합니다. Math.max.apply()도 같은 방식으로 동작하며 최대 값을 리턴합니다.

const arr = [30, 40, 10, 20];

const min = Math.min.apply(null, arr);
const max = Math.max.apply(null, arr);

console.log(min);
console.log(max);
10
40

 

 

Comments