V
V
Vladimir2016-10-16 13:27:42
C++ / C#
Vladimir, 2016-10-16 13:27:42

Converting int to string?

Good day! There is a function that prints an int to standard output:

void	ft_putchar(char c)
{
  write(1, &c, 1);
}

void	ft_putnbr(int n)
{
  if (n < 0)
  {
    write(1, "-", 1);
    ft_putnbr(-n);
  }
  else if (n > 9)
  {
    ft_putnbr(n / 10);
    ft_putnbr(n % 10);
  }
  else
    ft_putchar(n + '0');
}

How can it be written without recursion? Do not offer built-in functions. The challenge is to figure out how to do it.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
R
Rsa97, 2016-10-16
@MasterGerold

void wrInt(int val) {
  int l = 1, v = val;
  if (v < 0) {
    write(1, "-", 1);
    v = -v;
  }
  while ((v = v/10) > 0)
    l *= 10;
  while (l > 0) {
    v = val % l;
    ft_putchar(v + '0');
    val -= v*10;
    l /= 10;
  }
}

P
Peter, 2016-10-16
@petermzg

abstract

if (!v)
     result = '0';
  else{
     while (v){
       ...
        v =  (v - (v % 10)) / 10; 
     }
  }

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question