728x90
반응형

백준알고리즘

- Bronze 5 -

 #11283. 한글 2 by JAVA and node.js 

 


 

문제

출처: https://www.acmicpc.net/problem/11283 

 


 

접근 방법

▶ JAVA: charAt()

▶ node.js: charCodeAt()


 

풀이

▶ JAVA

import java.util.*;

public class Main {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        String hanguel = scan.next();
        scan.close();
        System.out.println(hanguel.charAt(0)-44031);
    }
}

▶ node.js

var fs = require('fs');
var input = fs.readFileSync('/dev/stdin').toString().trim();
console.log(input.charCodeAt() - 44031);

node.js에서는 charAt()이 아닌 charCodeAt()을 사용한다.

자바에서는 charAt(0)을 사용하면서 왜 node.js에서는 charCodeAt()을 사용할까?

String str = "Hello World!";
System.out.println(str.charAt(0)); // 첫 번째 글자인 H 반환
System.out.println(str.charAt(0)-70); // H의 유니코드 72에서  71을 뺀 1 반환(A ~ Z : 65 ~ 90)

위에서 볼 수 있듯이 자바에서 charAt()은 문자열반환과 유니코드 계산이 동시에 가능하다.

하지만 javascript(node.js)에서는 charAt()은 문자열을, charCodeAt()은 코드값(int)을 반환하는 함수이다.

var str = 'Hello World!';
console.log('str.charAt() : ' + str.charAt());
console.log('str.charAt(0) : ' + str.charAt(0));
console.log('str.charAt(1) : ' + str.charAt(1));
console.log(str.charAt(0) - 71);
console.log(str.charCodeAt() - 71);
console.log(str.charCodeAt(0) - 71);
console.log(str.charCodeAt(1) - 71);

위 코드의 결과값을 보면 아래와 같다.

str.charCodeAt() 부분에 'str.charCodeAt() - 71 : ' + str.charCodeAt() - 71 형식으로 쓰지 못 한 이유는 저렇게 쓰게 되면 문자열로 인식해서 NaN이 뜬다. 그래서 결과를 비교하기 위해 값만 적었다.

네 번째와 다섯 번째 출력을 보면, charAt() - 71은 문자열 - 숫자 여서 NaN이 뜨고, charCodeAt() - 71은 숫자 - 숫자 여서 값이 정상적으로 나온 것을 알 수 있다.

 

백준 문제를 자바와 node.js 두 가지 방법으로 풀면서 javascript가 더 섬세한 느낌을 받는다.

단계를 늘려가면 더 많이 느낄 거 같다..


 

결과

 


 

 

 

 

 

End.

heisely's 괴발개발 개발일지

 

728x90
반응형

+ Recent posts