闲来无聊,自己写的itoa函数

本文分享了一道著名公司的面试题解答,作者用C语言重新实现了itoa函数,并计算了其时间复杂度。该实现支持多种进制,并在文章末尾提供了测试代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

某著名公司的一道面试题:
请用C语言将API函数itoa函数重写,并计算复杂度。
我花了半个小时写了一个,欢迎大家批评指正。

itoa.c (时间复杂度 = o(len), len为转换后的字符串长度)

char* itoa(int value, char* str, int radix)
{
    
int remainer = value;
    
int len = 0;
    
int i = 0;
    
    
const char temp[36= {'0''1''2''3'
                                                
'4''5''6''7'
                                                
'8''9''A''B',
                                                
'C''D''E''F',
                                                
'G''H''I''J',
                                                
'K''L''M''N',
                                                
'O''P''Q''R',
                                                
'S''T''U''V',
                                                
'W''X''Y''Z'
                                                }
;
    
    
if(str == NULL)
        
return str;
    
    remainer 
= value;
    
    
//calculate the length of string after value conversion    
    while((remainer = remainer / radix) != 0)
        len
++;
    
    
//add the prefix of string
    
//binary:     0B
    
//octal:         0O
    
//decimal:     0D
    
//Hex:            0X
    
//Other:         XX
    switch(radix)
    
{
        
case 2:
            str[
0= '0';
            str[
1= 'B';
            
break;
        
        
case 8:
            str[
0= '0';
            str[
1= 'O';
            
break;
        
        
case 10:
            str[
0= '0';
            str[
1= 'D';
            
break;
        
        
case 16:
            str[
0= '0';
            str[
1= 'X';
            
break;
        
        
default:
            str[
0= 'X';
            str[
1= 'X';
            
break;            
    }

    
    i 
= 2;
    
    remainer 
= value;
    
    
//data conversion
    while((remainer != 0|| (len >= 0))
    
{
        str[i
++= temp[remainer / (int)(pow(radix, len))];
        remainer 
= value % (int)(pow(radix, len));
        len
-- ;
    }

    str[i] 
= '

测试代码如下:

#include <math.h>
#include 
<stdio.h>

int main(int argc, char* argv[])
{
    
int value = 0;
        
    
char str[100];
    
    
    scanf(
"%d"&value);
    
    
while(value != 0)    
    
{
        printf(
"%d %s ", value, itoa(value, str, 2));
        printf(
"%d %s ", value, itoa(value, str, 8));
        printf(
"%d %s ", value, itoa(value, str, 10));
        printf(
"%d %s ", value, itoa(value, str, 16));
        
        scanf(
"%d"&value);
    }

    
    
return 1;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值