1006. 换个格式输出整数 (15)

1006. 换个格式输出整数 (15)
第一个是我写的,很麻烦。第二个是别人的简介方案。
在我的方案中,malloc()函数,来动态给指针分配内存。这里需要注意了,
第一:malloc分配内存没有初始化,而且尽量用memset()函数初始化为0(即’\0’)再赋值,不然程序会出现比较麻烦的问题,比如下面这个问题:
这里写图片描述
首先是分配内存大小比目标大小要大的原因(malloc函数说明传送门):
image_1bir2sbak4k31p4m11vp1gf01ugl9.png-38.5kB
其实是要注意,在C语言中,字符串都是要以‘\0’结尾。所以在分配内存后立即全部初始化为‘\0’是再好不过的了。
然后是strcat()函数在链接两个字符串时,也是以第一个字符串’\0’为起始点,第二字符串’\0’为终止点来连接的。如下图:
这里写图片描述

//coded by indere 2017/06/17

//让我们用字母B来表示“百”、字母S表示“十”,用“12...n”来表示个位数字n( < 10),换个格式来输出任一个不超过3位的正整数。例如234应该被输出为BBSSS1234,因为它有2个“百”、3个“十”、以及个位的4。
//
//  输入格式:每个测试输入包含1个测试用例,给出正整数n( < 1000)。
//
//  输出格式:每个测试用例的输出占一行,用规定的格式输出n。
//
//  输入样例1:
//  234
//  输出样例1:
//  BBSSS1234

//思路  先%10  后/10

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

#define MAXSIZE 30

void transNum(int num);

int main() {
    int testnum;
    scanf("%d", &testnum);
    transNum(testnum);
    return 0;
}

void transNum(int num) {
    int n = num;
    char *singleDigit = NULL;
    char *tensDigit = NULL;
    char *hundrendsDight = NULL;
    int temp;
    int count = 0;
    while (n != 0) {
        temp = n % 10;
        n = n / 10;
        if (count == 0) {   /*个位*/
            singleDigit = (char *)malloc(sizeof(char) *(temp + 1));
            for (int i = 0; i < temp ; i++)
                singleDigit[i] = (i + 1) + '0';
            singleDigit[temp] = 0;
            count++;
        }
        else if (count == 1) {  /*十位*/
            tensDigit = (char *)malloc(sizeof(char) * (temp + 1));
            memset(tensDigit, 'S', sizeof(char) * temp);
            tensDigit[temp] = 0;
            count++;
        }
        else if (count == 2) {  /*百位*/
            hundrendsDight = (char *)malloc(sizeof(char) * (temp + 1));
            memset(hundrendsDight, 'B', sizeof(char) * temp);
            hundrendsDight[temp] = 0;
            count++;
        }
    }
    char *sum = (char *)malloc(sizeof(char) * MAXSIZE);
    memset(sum,0,sizeof(char) * MAXSIZE);
    if (count >= 3) {
        strcat(sum,hundrendsDight);
    }
    if (count >= 2) {
        strcat(sum,tensDigit);
    }
    if (count >= 1) {
        strcat(sum,singleDigit);
    }
    printf("%s\n",sum);
    free(singleDigit);
    free(tensDigit);
    free(hundrendsDight);
    free(sum);
}

#include <stdio.h>
int main()
{
    int n;
    scanf("%d", &n);
    for(int i = 0; i < n / 100;     i++)    putchar('B');
    for(int i = 0; i < n / 10 % 10; i++)    putchar('S');
    for(int i = 0; i < n % 10;      i++)    putchar('1' + i);
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值