递归算法实现进制转换

1、十进制转换成二进制【递归法】
#include <stdio.h>

int decimal_to_binary(unsigned int number)
{
    return number == 0 ? 0 : number % 2 + 10 * decimal_to_binary(number / 2);
}

void test()
{
    const int sets[][2] = 
    {
        {0, 0}, {1, 1}, {2, 6}, {3, 11}, {5, 60}, {6, 10}, {7, 100},
    };

    for (int i = 0, size = sizeof(sets) / sizeof(sets[0]); i < size; ++i)
    {
        printf("res:%d\n",decimal_to_binary(sets[i][0]));
    }
}

int main()
{
    test();
    return 0;
}

测试结果:

binary[0] = 0
binary[1] = 1
binary[2] = 10
binary[3] = 11
binary[4] = 100
binary[5] = 110
binary[6] = 111
 

2、十进制转换成八进制【递归法】
#include <stdio.h>

int decimal_to_octal(int decimal)
{
    if ((decimal < 8) && (decimal > 0))
    {
        return decimal;
    }
    else if (decimal == 0)
    {
        return 0;
    }
    else
    {
        return ((decimal_to_octal(decimal / 8) * 10) + decimal % 8);
    }
}

int main()
{
    int octalNumber, decimalNumber;
    printf("\nEnter your decimal number : ");
    scanf("%d", &decimalNumber);
    octalNumber = decimal_to_octal(decimalNumber);
    printf("\nThe octal of %d is : %d", decimalNumber, octalNumber);

    return 0;
}

测试结果:

Enter your decimal number : 100

The octal of 100 is : 144

【欢迎关注编码小哥,学习更多实用的编程方法】

相关推荐

  1. 算法实现转换

    2024-01-21 08:40:06       65 阅读
  2. 算法笔记p93_转换

    2024-01-21 08:40:06       40 阅读
  3. (二).数值&转换

    2024-01-21 08:40:06       38 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-01-21 08:40:06       98 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-01-21 08:40:06       106 阅读
  3. 在Django里面运行非项目文件

    2024-01-21 08:40:06       87 阅读
  4. Python语言-面向对象

    2024-01-21 08:40:06       96 阅读

热门阅读

  1. 只用Mysql搞一个分布式锁

    2024-01-21 08:40:06       54 阅读
  2. C语言:函数指针的使用

    2024-01-21 08:40:06       57 阅读
  3. 网络卡问题排查手段

    2024-01-21 08:40:06       59 阅读
  4. [Linux] Ubuntu install Miniconda

    2024-01-21 08:40:06       63 阅读
  5. 科普大语言模型中的Embedding技术

    2024-01-21 08:40:06       54 阅读
  6. MySQL死锁场景与应对方案

    2024-01-21 08:40:06       59 阅读
  7. C#设计模式教程(10):装饰器模式

    2024-01-21 08:40:06       51 阅读
  8. Webpack5入门到原理15:提取 Css 成单独文件

    2024-01-21 08:40:06       53 阅读
  9. vue对axios进行二次封装

    2024-01-21 08:40:06       50 阅读