문제
https://www.acmicpc.net/problem/2257
풀이
1. Node.js(fs)
const fs = require('fs');
const input = fs.readFileSync('/dev/stdin').toString().trim();
const atomicMass = {
'H': 1,
'C': 12,
'O': 16
};
function calculateMass(formula) {
const stack = [];
for (let char of formula) {
if (char === '(') {
stack.push(char);
} else if (char === ')') {
let subMass = 0;
while (stack[stack.length - 1] !== '(') {
subMass += stack.pop();
}
stack.pop(); // Remove '('
stack.push(subMass);
} else if (char >= '2' && char <= '9') {
stack.push(stack.pop() * (char - '0'));
} else {
stack.push(atomicMass[char]);
}
}
return stack.reduce((sum, mass) => sum + mass, 0);
}
console.log(calculateMass(input));
2. Node.js(readLine)
const readline = require('readline');
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
const atomicMass = {
'H': 1,
'C': 12,
'O': 16
};
function calculateMass(formula) {
const stack = [];
for (let char of formula) {
if (char === '(') {
stack.push(char);
} else if (char === ')') {
let subMass = 0;
while (stack[stack.length - 1] !== '(') {
subMass += stack.pop();
}
stack.pop(); // Remove '('
stack.push(subMass);
} else if (char >= '2' && char <= '9') {
stack.push(stack.pop() * (char - '0'));
} else {
stack.push(atomicMass[char]);
}
}
return stack.reduce((sum, mass) => sum + mass, 0);
}
rl.on('line', (line) => {
console.log(calculateMass(line.trim()));
rl.close();
}).on('close', () => {
process.exit(0);
});
3. C#
using System;
using System.Collections.Generic;
class Program
{
static Dictionary<char, int> atomicMass = new Dictionary<char, int>
{
{'H', 1},
{'C', 12},
{'O', 16}
};
static void Main()
{
string formula = Console.ReadLine().Trim();
Console.WriteLine(CalculateMass(formula));
}
static int CalculateMass(string formula)
{
Stack<int> stack = new Stack<int>();
foreach (char c in formula)
{
if (c == '(')
{
stack.Push(-1); // Use -1 to represent '('
}
else if (c == ')')
{
int subMass = 0;
while (stack.Peek() != -1)
{
subMass += stack.Pop();
}
stack.Pop(); // Remove -1 (which represents '(')
stack.Push(subMass);
}
else if (c >= '2' && c <= '9')
{
stack.Push(stack.Pop() * (c - '0'));
}
else
{
stack.Push(atomicMass[c]);
}
}
return stack.Sum();
}
}
설명
- 입력 처리:
- 화학식을 문자열로 입력받습니다.
- 원자량 정의:
- H, C, O 각각의 원자량을 딕셔너리(또는 해시맵)로 정의합니다.
- 화학식량 계산 함수 (calculateMass 또는 CalculateMass):
- 스택을 사용하여 계산을 수행합니다.
- 문자열을 순회하면서 다음과 같이 처리합니다:
- '('를 만나면 스택에 push합니다 (C#에서는 -1로 표현).
- ')'를 만나면 '('까지의 모든 값을 더한 후 그 결과를 다시 스택에 push합니다.
- 숫자(2-9)를 만나면 직전의 값에 곱합니다.
- 원자(H, C, O)를 만나면 해당 원자의 질량을 스택에 push합니다.
- 최종적으로 스택에 있는 모든 값을 더하여 총 질량을 계산합니다.
- 결과 출력:
- 계산된 총 화학식량을 출력합니다.
문제
https://www.acmicpc.net/problem/2257
풀이
1. Node.js(fs)
const fs = require('fs');
const input = fs.readFileSync('/dev/stdin').toString().trim();
const atomicMass = {
'H': 1,
'C': 12,
'O': 16
};
function calculateMass(formula) {
const stack = [];
for (let char of formula) {
if (char === '(') {
stack.push(char);
} else if (char === ')') {
let subMass = 0;
while (stack[stack.length - 1] !== '(') {
subMass += stack.pop();
}
stack.pop(); // Remove '('
stack.push(subMass);
} else if (char >= '2' && char <= '9') {
stack.push(stack.pop() * (char - '0'));
} else {
stack.push(atomicMass[char]);
}
}
return stack.reduce((sum, mass) => sum + mass, 0);
}
console.log(calculateMass(input));
2. Node.js(readLine)
const readline = require('readline');
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
const atomicMass = {
'H': 1,
'C': 12,
'O': 16
};
function calculateMass(formula) {
const stack = [];
for (let char of formula) {
if (char === '(') {
stack.push(char);
} else if (char === ')') {
let subMass = 0;
while (stack[stack.length - 1] !== '(') {
subMass += stack.pop();
}
stack.pop(); // Remove '('
stack.push(subMass);
} else if (char >= '2' && char <= '9') {
stack.push(stack.pop() * (char - '0'));
} else {
stack.push(atomicMass[char]);
}
}
return stack.reduce((sum, mass) => sum + mass, 0);
}
rl.on('line', (line) => {
console.log(calculateMass(line.trim()));
rl.close();
}).on('close', () => {
process.exit(0);
});
3. C#
using System;
using System.Collections.Generic;
class Program
{
static Dictionary<char, int> atomicMass = new Dictionary<char, int>
{
{'H', 1},
{'C', 12},
{'O', 16}
};
static void Main()
{
string formula = Console.ReadLine().Trim();
Console.WriteLine(CalculateMass(formula));
}
static int CalculateMass(string formula)
{
Stack<int> stack = new Stack<int>();
foreach (char c in formula)
{
if (c == '(')
{
stack.Push(-1); // Use -1 to represent '('
}
else if (c == ')')
{
int subMass = 0;
while (stack.Peek() != -1)
{
subMass += stack.Pop();
}
stack.Pop(); // Remove -1 (which represents '(')
stack.Push(subMass);
}
else if (c >= '2' && c <= '9')
{
stack.Push(stack.Pop() * (c - '0'));
}
else
{
stack.Push(atomicMass[c]);
}
}
return stack.Sum();
}
}
설명
- 입력 처리:
- 화학식을 문자열로 입력받습니다.
- 원자량 정의:
- H, C, O 각각의 원자량을 딕셔너리(또는 해시맵)로 정의합니다.
- 화학식량 계산 함수 (calculateMass 또는 CalculateMass):
- 스택을 사용하여 계산을 수행합니다.
- 문자열을 순회하면서 다음과 같이 처리합니다:
- '('를 만나면 스택에 push합니다 (C#에서는 -1로 표현).
- ')'를 만나면 '('까지의 모든 값을 더한 후 그 결과를 다시 스택에 push합니다.
- 숫자(2-9)를 만나면 직전의 값에 곱합니다.
- 원자(H, C, O)를 만나면 해당 원자의 질량을 스택에 push합니다.
- 최종적으로 스택에 있는 모든 값을 더하여 총 질량을 계산합니다.
- 결과 출력:
- 계산된 총 화학식량을 출력합니다.