牛客网 华中科技大学 八进制

题目描述

输入一个整数,将其转换成八进制数输出。

输入描述:

输入包括一个整数N(0<=N<=100000)。

输出描述:

可能有多组测试数据,对于每组数据,
输出N的八进制表示数。

示例1

输入

7
8
9

输出

7
10
11

答案

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

int main()
{
    long int n;
    //printf("%s\n", 0);
    //printf("%d", 0);
    //利用while来读取每一个输入的数字,一直从读取数据,直到读到一个EOF标记为止
    while (scanf("%d", &n) != EOF)
    {
        if (n == 0)
        {
            printf("0\n");
            continue;
        }
        //初始化result数组,使每一个元素为(null)
        char result[12] = { 0 };        
        while (n)
        {
            int m = n % 8; 
            //初始化t数组,使每一个元素为(null)
            char t[2] = {0};
            //将int的m 转化为字符数组放入t中,将一些数据类型转为字符串数组
            sprintf(t, "%d", m);
            //字符串连接,将一部分字符串结果加入result中
            strcat(result, t);
            //除以8,取整,辗转相除法
            n= n / 8;
        }
        //字符串逆序,整数的辗转相除法,除完以后,数从下往上读=====字符串数组从后往前打印
        //取result数组中的内容的长度,即这个数组中非空元素的个数
        int len = strlen(result);
        //利用对称性,首尾交换,实现字符数组的倒置、字符串的倒置
        //从0开始到len/2,这已经包含奇偶的情况
        for (int i = 0; i < len/2; i++)
        {
            char tmp=result[i];
            result[i] = result[len-i -1];
            result[len-i-1] = tmp;
        }
        //printf("%s\n", strrev(result));//颠倒字符数组,但不知道为什么无法通过牛客网机试的环境
        printf("%s\n", result);         
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_37905259/article/details/81067795