📜  实现自己的itoa()

📅  最后修改于: 2021-05-26 00:37:21             🧑  作者: Mango

itoa函数将integer转换为以null终止的字符串。它也可以转换负数。 itoa函数的标准定义如下:-

char* itoa(int num, char* buffer, int base) 

第三个参数基数指定转换基数。例如:-如果base为2,则它将整数转换为其二进制兼容字符串;如果base为16,则它将创建整数的十六进制转换字符串形式。

如果base为10并且value为负,则结果字符串前面带有减号(-)。在任何其他基数下,值始终被认为是无符号的。

参考:http://www.cplusplus.com/reference/cstdlib/itoa/?kw=itoa

例子:

itoa(1567, str, 10) should return string "1567"
  itoa(-1567, str, 10) should return string "-1567"
  itoa(1567, str, 2) should return string "11000011111"
  itoa(1567, str, 16) should return string "61f"

给定数字的各个数字必须经过处理,并且其相应的字符必须放在给定的字符串。使用给定基数的重复除法,我们得到从最低有效位到最高有效位的各个数字。但是在输出中,这些数字需要相反的顺序。因此,我们将经过重复除法后获得的字符串反转并返回。

/* A C++ program to implement itoa() */
#include 
using namespace std;
  
/* A utility function to reverse a string  */
void reverse(char str[], int length)
{
    int start = 0;
    int end = length -1;
    while (start < end)
    {
        swap(*(str+start), *(str+end));
        start++;
        end--;
    }
}
  
// Implementation of itoa()
char* itoa(int num, char* str, int base)
{
    int i = 0;
    bool isNegative = false;
  
    /* Handle 0 explicitely, otherwise empty string is printed for 0 */
    if (num == 0)
    {
        str[i++] = '0';
        str[i] = '\0';
        return str;
    }
  
    // In standard itoa(), negative numbers are handled only with 
    // base 10. Otherwise numbers are considered unsigned.
    if (num < 0 && base == 10)
    {
        isNegative = true;
        num = -num;
    }
  
    // Process individual digits
    while (num != 0)
    {
        int rem = num % base;
        str[i++] = (rem > 9)? (rem-10) + 'a' : rem + '0';
        num = num/base;
    }
  
    // If number is negative, append '-'
    if (isNegative)
        str[i++] = '-';
  
    str[i] = '\0'; // Append string terminator
  
    // Reverse the string
    reverse(str, i);
  
    return str;
}
  
// Driver program to test implementation of itoa()
int main()
{
    char str[100];
    cout << "Base:10 " << itoa(1567, str, 10) << endl;
    cout << "Base:10 " << itoa(-1567, str, 10) << endl;
    cout << "Base:2 " << itoa(1567, str, 2) << endl;
    cout << "Base:8 " << itoa(1567, str, 8) << endl;
    cout << "Base:16 " << itoa(1567, str, 16) << endl;
    return 0;
}

输出:

Base:10 1567
Base:10 -1567
Base:2 11000011111
Base:8 3037
Base:16 61f
要从最佳影片策划和实践问题去学习,检查了C++基础课程为基础,以先进的C++和C++ STL课程基础加上STL。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程”