#include <stdio.h>
#include <stdlib.h>

    char* __private_to_binary_representation(int n, char* print_here, int pos) {
      //printf("pos %d, n %d\n", pos, n);
      if (n == 0) {
        return print_here;
      }
      print_here = __private_to_binary_representation(n >> 1, print_here, pos + 1);
      (*print_here) = (n & 1) + '0';
      //printf("pos %d, n %d, n & 1 %d, *print_here %c\n", pos, n, n & 1, *print_here);
      return print_here + 1;
    }

    char* to_binary_representation(int n, char* print_here) {
      int is_negative = n < 0? 1: 0;
      // primeiro, preencho o valor absoluto do número, então o primeiro bit sempre será 0
      char* null_terminator_pos = __private_to_binary_representation(abs(n), print_here + 1, 0);
      print_here[0] = '0';
      
      // garantindo o final da string
      (*null_terminator_pos) = '\0';
      
      if (is_negative) {
        char* bit_check;
        int bit1_found = 0;
        for (bit_check = null_terminator_pos - 1; bit_check >= print_here; bit_check--) {
          // troca os bits na representação de complemento de 2
          if (bit1_found) {
            (*bit_check) = (*bit_check) == '1'? '0': '1';
          } else if ((*bit_check) == '1') {
            bit1_found = 1;
          }
        }
      }
      return print_here;
    }

int main(void) {
	char buff[100];
	printf("to_binary_representation(%d), %s\n", 0, to_binary_representation(0, buff));
	printf("to_binary_representation(%d), %s\n", 1, to_binary_representation(1, buff));
	printf("to_binary_representation(%d), %s\n", 5, to_binary_representation(5, buff));
	printf("to_binary_representation(%d), %s\n", -5, to_binary_representation(-5, buff));
	printf("to_binary_representation(%d), %s\n", -1, to_binary_representation(-1, buff));
	return 0;
}
