12.整数转罗马数字

题目


思路
1.取出每一位数字
2.从高位向低位替换数字成对应的罗马数字
代码

//1维代表位数,2维分别表示1和5
char unit[][2] = {
  {'I', 'V'},
  {'X', 'L'},
  {'C', 'D'},
  {'M', 'N'},
};

char *intToRoman(int num) {
  int op;
  char *result = malloc(100);
  int step=0;
  char *head = result;
  int charstack[5];
  int *s = charstack;

  while (num) {
    *s++ = num % 10;
    num/=10;
    step++;
  }

  while (step>0) {
    op = *--s;//从高位取至低位
    --step;
    if (op <=3) {//小于4,有多少个添加多少个1
      while (op--) {
        *result++ = unit[step][0];
      }
    } else if (op==4) {//等于4组合5与1
      *result++ = unit[step][0];
      *result++ = unit[step][1];
    } else if (op<=8) {//大于4小于9组合5和op-5数量的1
      *result++ = unit[step][1];
      while (op-- > 5) {
        *result++ = unit[step][0];
      }
    } else { //op==9 组合高位1与当前位1
      *result++ = unit[step][0];
      *result++ = unit[step+1][0];
    }
  }
  *result = '\0';

  return head;
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容