在不访问库的情况下将整数转换为字符串 [英] Convert integer to string without access to libraries

查看:20
本文介绍了在不访问库的情况下将整数转换为字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近阅读了一个样本求职面试问题:

I recently read a sample job interview question:

写一个函数来转换一个整数到一个字符串.假设你没有访问库函数,即itoa() 等...

Write a function to convert an integer to a string. Assume you do not have access to library functions i.e., itoa(), etc...

你会怎么做?

推荐答案

快速解决:(编辑处理负数)

fast stab at it: (edited to handle negative numbers)

int n = INT_MIN;
char buffer[50];
int i = 0;

bool isNeg = n<0;

unsigned int n1 = isNeg ? -n : n;

while(n1!=0)
{
    buffer[i++] = n1%10+'0';
    n1=n1/10;
}

if(isNeg)
    buffer[i++] = '-';

buffer[i] = '';

for(int t = 0; t < i/2; t++)
{
    buffer[t] ^= buffer[i-t-1];
    buffer[i-t-1] ^= buffer[t];
    buffer[t] ^= buffer[i-t-1];
}

if(n == 0)
{
    buffer[0] = '0';
    buffer[1] = '';
}   

printf(buffer);

这篇关于在不访问库的情况下将整数转换为字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆