Node.js 백준 알고리즘 9

김승우·2021년 6월 16일
0

🎉 2021.06.16 문자열

1. 11654 - 아스키 코드

const fs = require('fs');
const input = fs.readFileSync('/dev/stdin');

function getCharCode(value) {
    return String.prototype.charCodeAt.call(value, 0);
}

console.log(getCharCode(input));

String.prototype.charCodeAt(index)는 index에 해당하는 문자의 아스키코드값을 반환하는 함수이다.
반대되는 함수로 String.fromCharCode()가 있다.

2. 11720 - 숫자의 합

const fs = require('fs');
const input = fs.readFileSync('/dev/stdin').toString().split('\n');

const length = Number(input[0]),
      numbers = input[1];

let sum = i = 0;

for(i; i < length; i++) {
    sum += Number(numbers[i]);
}

console.log(sum);

3. 10809 - 알파벳 찾기

  • 처음 풀이
const fs = require('fs');
const input = fs.readFileSync('/dev/stdin').toString();

// 소문자 a의 아스키 코드 값
const aCode = 97;
const zCode = 122;

// a ~ z에 해당하는 인덱스의 값을 -1로 모두 초기화 시킨 배열
let alphabetArr = [];

for(let i = 0, _length = zCode - aCode + 1; i < _length; i++) {
    alphabetArr[i] = -1;
}

for(let j = 0; j < input.length; j++){
    const _index = String.prototype.charCodeAt.call(input[j]) - aCode;
    
    if(alphabetArr[_index] > -1) {
        continue;
    } else {
        alphabetArr[_index] = j;
    }
}

console.log(alphabetArr.join(' '));
  • 최종 제출
const fs = require('fs');
const input = fs.readFileSync('/dev/stdin').toString();

const result = [];

// 97은 a의 아스키 코드
// 122는 z의 아스키 코드
for(let i = 97; i <= 122; i++) {
    const ch = String.fromCharCode(i);
    const _index = input.indexOf(ch);

    result.push(_index);
}

console.log(result.join(' '));
profile
사람들에게 좋은 경험을 선사하고 싶은 주니어 프론트엔드 개발자

0개의 댓글