► JS Algorithm/Programmers

[Programmers] JavaScript 알고리즘 | Lv.0 숫자 찾기

다람트리 2024. 1. 12. 20:46
반응형

🔒 문제 설명

정수 num k 매개변수로 주어질 , num 이루는 숫자 중에 k 있으면 num 숫자가 있는 자리 수를 return하고 없으면 -1 return 하도록 solution 함수를 완성해보세요.


🔒 제한사항  

  • 0 < num < 1,000,000
  • 0 ≤ k < 10
  • num k 여러 있으면 가장 처음 나타나는 자리를 return 합니다.

🔒 입출력 예

num k result
29183 1 3
232443 4 4
123456 7 -1

🔒 입출력 예 설명

입출력 예 #1

  • 29183에서 1은 3번째에 있습니다.

입출력 예 #2

  • 232443에서 4는 4번째에 처음 등장합니다.

입출력 예 #3

  • 123456 7 없으므로 -1 return 합니다.

 

🔐 solution of mine

Array.indexOf()

  const solution = (num, k) =>
    console.log(
      [...(num + "")].indexOf("" + k) === -1
        ? -1
        : [...(num + "")].indexOf("" + k) + 1
    );

  solution(29183, 1); // expected output: 3
  solution(232443, 4); // expected output: 4
  solution(123456, 7); // expected output: -1

 


 

🔐 solution of others 

Number.toString()

String.split()
Array.map()
Number()
Array.indexOf()
  const solution = (num, k) =>
    console.log(
      num
        .toString()
        .split("")
        .map((el) => Number(el))
        .indexOf(k) + 1 || -1
    );

  solution(29183, 1); // expected output: 3
  solution(232443, 4); // expected output: 4
  solution(123456, 7); // expected output: -1

 

🔐 solution of others 

+"" (숫자를 문자로 바꾸는 방법)

String.includes()

String.indexOf()

  const solution = (num, k) => {
    let aaa = num + "";
    if (aaa.includes(k)) {
      return console.log(aaa.indexOf(k) + 1);
    }
    return console.log(-1);
  };

  solution(29183, 1); // expected output: 3
  solution(232443, 4); // expected output: 4
  solution(123456, 7); // expected output: -1

 


 

반응형