findPosition.js (8kyu 29)

Codewars 알고리즘 풀이


Description

  • When provided with a letter, return its position in the alphabet.
    • 알파벳의 위치를 반환한다.



Solution 01

function findPosition(letter) {
  const alphabet = 'abcdefghijklmnopqrstuvwxyz';
  
  return 'Position of alphabet: ' + (alphabet.indexOf(letter) + 1);
}

findPosition('a');  // 1
findPosition('b');  // 2
findPosition('c');  // 3
findPosition('d');  // 4
findPosition('x');  // 24
findPosition('z');  // 26


Solution 02

function findPosition(letter) {
  const alphabet = 'abcdefghijklmnopqrstuvwxyz';
  
  return `Position of alphabet: ${alphabet.indexOf(letter) + 1}`;
}

findPosition('a');  // 1
findPosition('b');  // 2
findPosition('c');  // 3
findPosition('d');  // 4
findPosition('x');  // 24
findPosition('z');  // 26


Solution 03

function findPosition(letter) {
  const alphabet = '@abcdefghijklmnopqrstuvwxyz';
  
  return `Position of alphabet: ${alphabet.indexOf(letter)}`;
}

findPosition('a');  // 1
findPosition('b');  // 2
findPosition('c');  // 3
findPosition('d');  // 4
findPosition('x');  // 24
findPosition('z');  // 26


Solution 04

function findPosition(letter) {
  return `Position of alphabet: ${letter.charCodeAt(0) - 96}`;
}

findPosition('a');  // 1
findPosition('b');  // 2
findPosition('c');  // 3
findPosition('d');  // 4
findPosition('x');  // 24
findPosition('z');  // 26