2023 주니어 SRE 엔지니어 후레임

반응형

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

 

(런타임 에러로 현재 수정중입니다.)

 

이진수 덧셈입니다.

 

말그대로, 이진수 두 개를 입력받아 더한 뒤 결과값을 출력해주는 간단한 프로그램입니다.

 

본래 출제자의 목적은 1+1을 했을 때 carry를 발생시키는 것이겠지만,

 

저는 그런 건 다 무시하고 일단 10진법으로 변한 뒤 더해서

 

다시 2진법으로 변환했습니다.

 

 

머리가 나쁘면 몸이 고생한다는 게 이런 걸까요...

 

어쨌거나 소스 보시죠.

 

 

import java.util.Scanner;

public class Main {

	public static void main(String[] args) {

		int cnt=1;

		Scanner sc = new Scanner(System.in);
		int n1 = sc.nextInt();
		int n2 = sc.nextInt();
		
		String str1 = Integer.toString(n1);
		String str2 = Integer.toString(n2);

		long real1=0, real2=0, total=0;
		
		if(str1.equals("0") && str2.equals("0"))
			System.out.println(0);
		else {
			
			//n1 10진수 변환
			for(int i=str1.length()-1; i>=0; i--) { 
				if(str1.substring(i,i+1).equals("1"))
					real1 += cnt;
				cnt*=2; // cnt=1,2,4,8,16,32,64,...
			}

			cnt=1; // cnt 초기화
			
			//n2 10진수 변환
			for(int i=str2.length()-1; i>=0; i--) { 
				if(str2.substring(i,i+1).equals("1"))
					real2 += cnt;
				cnt*=2;
			}
			
			// n1+n2
			total = real1 + real2;
			
			String str_t="";
			
			// n1+n2 2진수 변환
			while(true) {
				// 10진수 -> 2진수 변환법을 이용하여 한 글자씩 str_t에 붙이기
				str_t = String.valueOf(total%2).concat(str_t);
				if(total==1)
					break;
				else
					total /= 2;
			}
			
			System.out.println(str_t);
		}
		
	}
}
반응형

이 글을 공유합시다

facebook twitter googleplus kakaoTalk kakaostory naver band