문제 링크입니다: https://www.acmicpc.net/problem/4388
4388번: 받아올림
어린이에게 여러자리 숫자의 덧셈을 가르칠 때는 오른쪽 자리부터 왼쪽으로 하나씩 계산하는 방법을 가르쳐준다. 이때, 받아올림이 발생하게 되며 아이들은 여기서 혼란에 빠진다. 받아올림이
www.acmicpc.net
각 자리 수를 더해봐야하므로 문자열로 변환하여 연산했습니다.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <string> | |
#include <algorithm> | |
using namespace std; | |
int getCarryCnt(int a, int b) | |
{ | |
string num = to_string(a); | |
string num2 = to_string(b); | |
reverse(num.begin(), num.end()); | |
reverse(num2.begin(), num2.end()); | |
int carryCnt = 0; | |
bool carry = false; | |
for (int i = 0; i < min(num.size(), num2.size()); i++) | |
{ | |
int sum = (num[i] - '0') + (num2[i] - '0') + carry; | |
if (sum >= 10) | |
{ | |
carry = true; | |
carryCnt++; | |
} | |
else | |
{ | |
carry = false; | |
} | |
} | |
for (int i = (num.size() > num2.size() ? num2.size() : num.size()); i < (num.size() > num2.size() ? num.size() : num2.size()); i++) | |
{ | |
int sum = num.size() > num2.size() ? num[i] : num2[i] + carry; | |
if (sum >= 10) | |
{ | |
carry = true; | |
carryCnt++; | |
} | |
else | |
{ | |
carry = false; | |
} | |
} | |
return carryCnt; | |
} | |
int main(void) | |
{ | |
ios_base::sync_with_stdio(0); | |
cin.tie(0); | |
while (1) | |
{ | |
int a, b; | |
cin >> a >> b; | |
if (a == 0 && b == 0) | |
{ | |
break; | |
} | |
cout << getCarryCnt(a, b) << "\n"; | |
} | |
return 0; | |
} |


개발환경:Visual Studio 2017
지적, 조언, 질문 환영입니다! 댓글 남겨주세요~
반응형
'알고리즘 > BOJ' 카테고리의 다른 글
백준 4504번 배수 찾기 (0) | 2021.05.15 |
---|---|
백준 4493번 가위 바위 보? (0) | 2021.05.15 |
백준 4153번 직각삼각형 (0) | 2021.05.15 |
백준 4101번 크냐? (0) | 2021.05.15 |
백준 4084번 Viva la Diferencia (0) | 2021.05.15 |