轮子

2020-03-17  本文已影响0人  孤烛

1.给定整数,正序转化为字符串

char *s num2str (int num) {
    char *s = malloc(20);
    int len = 0;
    while (num>0) {
      int a = num % 10;
      num /= 10;
      s[len++] = a + '0';
    }
    return s;
}

2.给定整数,逆序转化为字符串

char* num2str(int num) {
    char *s = malloc(20);
    memset(s, 0, 20);
    int len = 0;
    while (num>0) {
        int a = num % 10;
        num /= 10;
        s[len++] = a + '0';
    }

    for (int i = 0;i < len / 2; i++) {
        char tmp = s[i];
        s[i] = s[len - i - 1];
        s[len - i - 1] = tmp;
    }
    return s;
}

3.字符串申请大小要+1

上一篇下一篇

猜你喜欢

热点阅读