[BOJ/C++] 2089 -2진수

Hanbi·2023년 7월 23일
0

Problem Solving

목록 보기
77/108
post-thumbnail

문제

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

풀이

간단하지만 c언어가 몫 구할 때 소수점 버림 방식을 택한다는 사실을 알아야 풀 수 있음

-2로 나눠가며 구하지만,
n이 홀수인 경우에는 내림을 할 수 있도록 n--를 해준 후, -2로 나눠야한다.

코드

#include <iostream>
#include <string>

using namespace std;

int main() {
	int n;
	string ans;

	cin >> n;
	if (n == 0) {
		cout << 0;

		return 0;
	}

	while (n != 0) {
		if (n % -2 == 0) {
			ans.insert(0, "0");
			n /= -2;
		}
		else {
			ans.insert(0, "1");
			n--;
			n /= -2;
		}
	}

	cout << ans;

	return 0;
}
profile
👩🏻‍💻

1개의 댓글

comment-user-thumbnail
2023년 7월 23일

정보 감사합니다.

답글 달기