728x90
공부하다가 그냥 해본 문자열 숫자 곱하기
숫자 범위가 너무 클 경우 unsigned long long 자료형을 사용해도 계산이 안될 때가 있다.
그럴 때는 문자열을 사용해야된다.
#include <iostream>
#include <string>
using namespace std;
string calculate_add(string a, string b) {
if (a.size() == 0 )
return b;
if (b.size() == 0 )
return a;
string big_num = a.size() > b.size() ? a : b;
string small_num = a.size() > b.size() ? b : a;
string addResult = "";
int round = 0;
int s_idx = small_num.size() - 1;
int b_idx = big_num.size() - 1;
while (s_idx >= 0) {
int bnum = big_num[b_idx] - '0';
int snum = small_num[s_idx] - '0';
int result = bnum + snum;
int ten_unit = result / 10;
int one_unit = result % 10;
if (round) {
one_unit += round;
ten_unit += one_unit / 10;
one_unit = one_unit % 10;
}
addResult = to_string(one_unit) + addResult;
if (ten_unit) {
round = ten_unit;
}
else
round = 0;
s_idx--;
b_idx--;
}
while (b_idx >= 0) {
if (round) {
int bnum = big_num[b_idx] - '0';
int result = bnum + round;
int ten_unit = result / 10;
int one_unit = result % 10;
addResult = to_string(one_unit) + addResult;
if (ten_unit) {
round = ten_unit;
}
else
round = 0;
}
else
addResult = big_num[b_idx] + addResult;
b_idx--;
}
if (round) {
addResult = to_string(round) + addResult;
}
return addResult;
}
string calculate_mult(string base_num, string mult_num) {
int base_len = base_num.size();
int mult_num_len = mult_num.size();
string multResult = "";
for (int i = mult_num_len - 1; i >= 0; i--) {
int multnum = mult_num[i] - '0';
int round = 0;
string tempResult = "";
for (int k = 1; k < mult_num_len - i; k++) {
tempResult += "0";
}
for (int j = base_len - 1; j >= 0; j--) {
int basenum = base_num[j] - '0';
int result = multnum * basenum;
int ten_unit = result / 10;
int one_unit = result % 10;
if (round) {
one_unit += round;
ten_unit += one_unit / 10;
one_unit = one_unit % 10;
}
tempResult = to_string(one_unit) + tempResult;
if (ten_unit) {
round = ten_unit;
}
else
round = 0;
}
if (round) {
tempResult = to_string(round) + tempResult;
}
multResult = calculate_add(multResult, tempResult);
}
return multResult;
}
int main(void) {
string a, b;
cin >> a >> b;
cout << calculate_mult(a, b);
}




계산기로는 나오지 않을 숫자도 잘 나오는 걸 볼 수 있다.

728x90
'컴터 > C, C++' 카테고리의 다른 글
[C, C++] Pointer(포인터) ( 부제 : 어디서 삿대질) (0) | 2023.08.13 |
---|---|
c++ at(-1), [-1] 뭐는 되고? 왜 다르지? (0) | 2023.02.25 |
c++ string :: npos 는 -1 ? (0) | 2023.02.23 |