C++

[백준 알고리즘] 10757번 : 큰 수 A+B, c++

2022. 1. 22. 23:02

https://www.acmicpc.net/problem/10757

 

10757번: 큰 수 A+B

두 정수 A와 B를 입력받은 다음, A+B를 출력하는 프로그램을 작성하시오.

www.acmicpc.net

c++로 백준 10757번 문제를 풀어보겠다.

 

 

 

 

 

 

문제

두 정수 A와 B를 입력받은 다음, A+B를 출력하는 프로그램을 작성하시오.

입력

첫째 줄에 A와 B가 주어진다. (0 < A,B < 1010000)

출력

첫째 줄에 A+B를 출력한다.

예제 입력 1 복사

9223372036854775807 9223372036854775808

예제 출력 1 복사

18446744073709551615

 

 

 

 

<문제 풀이>

내가 작성한 코드는 다음과 같다.

 

#include <iostream>
#include <string>
using namespace std;
int main() {
    string str1;
    string str2;
    cin >> str1;
    cin >> str2;
    
    string newstr = "";
    int str1int = str1.length()-1;
    int str2int = str2.length()-1;
    int strint = 0;
    while(true) {
        if(str1int>=0 && str2int >=0) {
            if(str1[str1int]-48 + str2[str2int]-48 + strint >= 10) {
                newstr =  static_cast<char>(((str1[str1int]-48 + str2[str2int]-48 + strint)%10)+48)
                    + newstr;
                strint = 1;          
            }
            else {
                newstr =  static_cast<char>(((str1[str1int]-48 + str2[str2int]-48 + strint)%10)+48)
                    + newstr;
                strint = 0;
            }            
        }
        else if(str1int>=0 && str2int <0) {
            if(str1[str1int]-48 + strint >= 10) {
                newstr =  static_cast<char>(((str1[str1int]-48 + strint)%10)+48) + newstr;
                strint = 1;          
            }
            else {
                newstr =  static_cast<char>(((str1[str1int]-48 + strint)%10)+48) + newstr;
                strint = 0;
            }            
        }
        else if(str1int<0 && str2int >=0) {
            if(str2[str2int]-48 + strint >= 10) {
                newstr =  static_cast<char>(((str2[str2int]-48 + strint)%10)+48) + newstr;
                strint = 1;          
            }
            else {
                newstr =  static_cast<char>(((str2[str2int]-48 + strint)%10)+48) + newstr;
                strint = 0;
            }            
        }      
        else if(str1int==0 && str2int==0) {
            if(str1[str1int]-48 + str2[str2int]-48 + strint >= 10) {
                newstr =  static_cast<char>(((str1[str1int]-48 +str2[str2int]-48 + 
                                              strint)%10)+48) + newstr;
                newstr =  '1' + newstr;
                break;        
            }
            else {
                newstr =  static_cast<char>(((str1[str1int]-48 + str2[str2int]-48 + 
                                              strint)%10)+48) + newstr;
                break;
            }                           
        }
        else if(str1int<0 && str2int <0) {
            break;
        }        
        str1int--;
        str2int--;
    }
    
    cout << newstr;
    return 0;
}

 

입력값이 int 정수형으로 해결할 수 없는 크기이다보니 string의 문자열형태로 입력받고 해결하려는 시도는 좋았다.

 

하지만 발생할 수 있는 모든 경우를 다 나누어 모두 코드로 해결하려다보니 코드의 길이도 길어지고, 점점 복잡해졌다. 

실행해봤을 때도 잘못되었다고 나오는데 여러 조건들이 복잡하게 있다보니 코드를 수정하는데에도 어려움이 있었다.

 

 

 

코드를 작성하다보니 굳이 경우의 수를 나누지 않고도 간단하게 코드를 짤 수 있다는 것을 알게되었다.

 

마지막으로 작성해 완성한 코드는 다음과 같다.

 

1. string 문자열의 str1, str2을 선언한 후 입력받는다.

2. while 문을 str1int 또는 str2int 둘 중 하나라도 0이라면 반복하도록 해 반복한다.

- while 문 코드 내용 -

str1과 str2의 맨 뒤에 있는 숫자 하나씩을 꺼내온다.

꺼내온 숫자 2개와 올림수를 더한다.

그렇게 만들어진 수를 10으로 나누어, 몫은 또 올림수가 되어 다음으로 넘어가도록 하고, 나머지는 newstr에 저장한다.

3. 만약 아직 올림수가 0보다 크다면, newstr에 올림수만큼을 추가해준다.

4. 계산 후의 값으로 이루어진, 새로 만든 문자열 newstr을 뒤에서부터 하나씩 출력한다.

 

 

#include <iostream>
#include <string>
using namespace std;
int main() {
  string str1, str2, newstr; 
  cin >> str1 >> str2;
    
  int strint = 0;  
  int str1int = str1.length();  
  int str2int = str2.length();  
  while(str1int>0 || str2int>0) {
      
    int result1 = 0;  
    if(str1int>0)
      result1 = str1[--str1int]-48;  
      
    int result2 = 0;
    if(str2int>0)
      result2 = str2[--str2int]-48;
      
    int calculate = result1 + result2 + strint;  
    strint = calculate / 10; 
    calculate %= 10;
    char ch = calculate + 48;  
    newstr += ch;
  }
    
  if(strint>0)
    newstr+=strint+48;
    
  for(int i=newstr.length()-1;i>=0;i--)  
    cout << newstr[i];
   
  return 0;
}