[BaekJoon] 33557번 - 곱셈을 누가 이렇게 해 ㅋㅋ [Java][C++]
[BaekJoon] 33557번 - 곱셈을 누가 이렇게 해 ㅋㅋ [Java][C++]
1. 문제 풀이
주어진 두 연산이 동일한 결과를 내는지 판단하는 문제로 $A$, $B$ 를 문자열로 다루어서 해결했다. 두 수의 곱은 정수 타입 오버플로우만 주의하면 되고, 이상한 곱셈은 더 짧은 수의 앞에 $1$ 을 길이가 맞을 때까지 넣어줘서 곱셈을 편하게 할 수 있게 해주었다.
2. 코드
1. 풀이 [Java]
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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringBuilder sb = new StringBuilder();
StringTokenizer st;
int t = Integer.parseInt(br.readLine());
while (t-- > 0) {
st = new StringTokenizer(br.readLine());
String a = st.nextToken();
String b = st.nextToken();
String s1 = String.valueOf(Long.parseLong(a) * Long.parseLong(b));
int len = Math.max(a.length(), b.length());
int[] arrA = toArr(Integer.parseInt(a), len);
int[] arrB = toArr(Integer.parseInt(b), len);
StringBuilder tmp = new StringBuilder();
for (int i = 0; i < len; i++) {
tmp.append(arrA[i] * arrB[i]);
}
String s2 = tmp.toString();
if (s1.equals(s2)) {
sb.append("1\n");
} else {
sb.append("0\n");
}
}
System.out.println(sb);
}
static int[] toArr(int x, int len) {
int[] arr = new int[len];
int idx = len - 1;
while (x > 0) {
arr[idx--] = x % 10;
x /= 10;
}
while (idx >= 0) {
arr[idx--] = 1;
}
return arr;
}
}
2. 풀이 [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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int t;
cin >> t;
while (t--) {
string a, b;
cin >> a >> b;
string s1 = to_string(stoll(a) * stoll(b));
int len = max(a.size(), b.size());
vector<int> a2;
vector<int> b2;
for (int i = 0; i < ((int)a.size() - (int)b.size()); i++) {
b2.push_back(1);
}
for (int i = 0; i < ((int)b.size() - (int)a.size()); i++) {
a2.push_back(1);
}
for (char c : a) {
a2.push_back(c - '0');
}
for (char c : b) {
b2.push_back(c - '0');
}
string s2;
for (int i = 0; i < len; i++) {
s2 += to_string(a2[i] * b2[i]);
}
cout << (s1 == s2) << '\n';
}
}
This post is licensed under CC BY 4.0 by the author.