-2진수

BiBi·2021년 1월 21일
0

코딩테스트연습

목록 보기
48/66

0일 경우를 생각 못했다.

#include <algorithm>
#include <iostream>
#include <stdio.h>
#include <vector>
#include <map>
#include <stack>
#include <queue>
#include <deque>
#include <string>
#include <cmath>
using namespace std;



int main() {
	//freopen("input.txt", "rt", stdin);
	long long n;
	cin >> n;
	stack<int> s;
	if (n == 0) {
		printf("0");
			return 0;
	}
	while (n != 0) {
		if (n < 0 && n % 2 != 0) {
			n = ((n * -1) + 1) / 2;
			s.push(1);
		}
		else if (n < 0 && n % 2 == 0) {
			n = (n * -1) / 2;
			s.push(0);
		}
		else if (n > 0 && n % 2 != 0) {
			n = n / (-2);
			s.push(1);
		}
		else if (n > 0 && n % 2 == 0) {
			n = n / (-2);
			s.push(0);
		}
	}
	long long sts = s.size();
	for (long long i = 0; i < sts; i++) {
		printf("%d", s.top());
		s.pop();
	}
	


	return 0;
}
profile
Server Network Engineer

0개의 댓글