演習 4-12

無職の間にK&Rを再読。演習問題の解答をさらす。解く順番は適当。

演習4-12
printd のアイデアを使って itoa再帰版を書け。すなわち、再帰ルーチンを呼ぶことによって整数を文字列に変換せよ。


Exercise 4-12
Adapt the ideas of printd to write a recursive version of itoa; that is, convert an integer into a string by calling a recursive routine.

SICP をやりながらこういうのをやると、複雑な気分になる。

#include <stdio.h>

/* Answer */
int itoa(int n, char s[])
{
  int pos = 0;
  
  if (n / 10)
    pos = itoa(n / 10, s);
  else if (n < 0)
    s[pos++] = '-';
    
  s[pos++] = (n < 0 ? -n : n) % 10 + '0';
  s[pos] = '\0';

  return pos;
}


int main(void)
{
  char str[100];
  int num, len;

  num = 1234;
  len = itoa(num, str);
  printf("itoa(%d) => [%s] %d\n", num, str, len);

  num = -5678;
  len = itoa(num, str);
  printf("itoa(%d) => [%s] %d\n", num, str, len);

  num = 0;
  len = itoa(num, str);
  printf("itoa(%d) => [%s] %d\n", num, str, len);

  return 0;
}