[백준 23343] JavaScript (C#, C++) - soo:bak
작성일 :
문제 링크
설명
두 문자열 x와 y가 주어질 때, JavaScript의 빼기 연산처럼 계산한 결과를 출력하는 문제입니다.
문자열에 알파벳이 포함되면 숫자로 변환할 수 없어 NaN이 됩니다. 어느 한쪽이라도 NaN이면 결과도 NaN이고, 둘 다 숫자면 정수 뺄셈 결과를 출력합니다.
접근법
먼저, 두 문자열에 알파벳이 있는지 확인합니다. 하나라도 알파벳이 있으면 NaN을 출력합니다.
다음으로, 둘 다 알파벳이 없으면 정수로 변환한 후 빼기 연산을 수행합니다.
문자열 길이가 6 미만이므로 정수 범위 내에서 안전하게 계산할 수 있습니다.
Code
C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
using System;
namespace Solution {
class Program {
static void Main(string[] args) {
var parts = Console.ReadLine()!.Split();
var x = parts[0];
var y = parts[1];
var nan = false;
foreach (var ch in x) if (char.IsLetter(ch)) nan = true;
foreach (var ch in y) if (char.IsLetter(ch)) nan = true;
if (nan) Console.WriteLine("NaN");
else {
var a = int.Parse(x);
var b = int.Parse(y);
Console.WriteLine(a - b);
}
}
}
}
C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <bits/stdc++.h>
using namespace std;
bool hasAlpha(const string& s) {
for (char ch : s)
if (isalpha(static_cast<unsigned char>(ch)))
return true;
return false;
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
string x, y; cin >> x >> y;
if (hasAlpha(x) || hasAlpha(y)) cout << "NaN\n";
else {
int a = stoi(x);
int b = stoi(y);
cout << a - b << "\n";
}
return 0;
}