반응형

문제 출처 :


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



알고리즘 분석 :


문제 해결에 필요한 사항

1. BigInteger library

2. 이진수


알고리즘은 다음과 같다.


2진수 a,b 입력을 받고 -> a,b를 10진수로 변환 -> 두 수를 더하고 -> 이 수를 이진수로 변환시킨다.


이때 BigInteger 라이브러리를 통해 큰 수를 쉽게 해결한다.(정답이 80자리 2진수 일 수 있기에)


알고리즘 코드는 아래에 주석으로 수록해 두었다.






소스 코드 : 


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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
package JavaBasic;
 
import java.math.BigInteger;
import java.util.Scanner;
 
public class Jmain {
         
    public static void main(String[] args)
    {
        BigInteger a ;
        BigInteger b ;
        
        Scanner sc = new Scanner(System.in);
 
        a = sc.nextBigInteger();
        b = sc.nextBigInteger();
 
        if(a.compareTo(BigInteger.ZERO) == && b.compareTo(BigInteger.ZERO) == 0)
        {
            System.out.println("0");
            System.exit(0);
        }
            
        BigInteger decA = BigInteger.valueOf(0);
        BigInteger decB = BigInteger.valueOf(0);
        
        BigInteger cnt = new BigInteger("1");
        
        int lenA = a.toString().length();
        int lenB = b.toString().length();
        
        // 2진수 a를 10진수 decA로 바꾸는 과정
        for(int i = ; i < lenA; i ++)
        {
            BigInteger tmp = a.mod(BigInteger.valueOf(10));
            
            decA = decA.add(tmp.multiply(cnt));
            a = a.divide(BigInteger.valueOf(10));
            
            cnt = cnt.multiply(BigInteger.valueOf(2));
        }
        
        cnt = BigInteger.valueOf(1);
 
        // 2진수 b를 10진수 decB로 바꾸는 과정
        for(int i = ; i < lenB; i ++)
        {
            BigInteger tmp = b.mod(BigInteger.valueOf(10));
            
            decB = decB.add(tmp.multiply(cnt));
            b = b.divide(BigInteger.valueOf(10));
            
            cnt = cnt.multiply(BigInteger.valueOf(2));
        }
 
        
        // 10진수 a + b를 a에 저장해준다.
        decA = decA.add(decB);
        String str = new String();
        
        // decA가 0이 될때까지 계속 나누어준다(2진수로 변환)
        while(decA != BigInteger.valueOf(0))
        {
            str += decA.mod(BigInteger.valueOf(2));
            
            decA = decA.divide(BigInteger.valueOf(2));
        }
        
        // 뒤집어진 2진수를 역으로 출력
        for(int i = str.length() - 1; i >= 0; i --)
            System.out.print(str.charAt(i));
    }
    
}
 
//                                                       This source code Copyright belongs to Crocus
//                                                        If you want to see more? click here >>
Crocus


반응형

'Applied > 알고리즘 문제풀이' 카테고리의 다른 글

[9177번] 단어 섞기  (0) 2017.04.15
[1850번] 최대공약수  (0) 2017.04.14
[1574번] 룩 어택  (0) 2017.04.14
[1760번] N-Rook  (0) 2017.04.14
[1671번] 상어의 저녁식사  (0) 2017.04.14