data-structures - 如何最好地实现 itoa 和 atoi?
问题描述
C/C++ 库带有两个函数,即“itoa”和“atoi”——前者将整数值转换为字符数组。后者对包含数值的字符串数组执行反之亦然。任一函数中的数值可以是正整数或负整数。
我实现的功能如下:- itoa 功能
#include <iostream>
#include <algorithm>
void my_itoa(int num, char* str)
{
bool isNeg=false;
if(num < 0)
isNeg = true;
int idx = 0;
do {
int j = num % 10;
j = j < 0 ? j * -1 : j ;
str[idx++]=j+48;
num=num/10;
} while (num!=0);
if(isNeg)
str[idx++]='-';
str[idx]='\0';
std::reverse(str, str+idx);
}
atoi 函数
void my_atoi(char* str,int& i)
{
bool isNeg = false;
if(*str == '-') {
isNeg=true;
str++;
}
i=0;
while(*str!='\0') {
i =i*10 + (*str - 48);
str++;
}
if(isNeg)
i=i*-1;
}
驱动程序代码
int main()
{
char str[100];
my_itoa(-1234, str);
std::cout << "Str =" << str << std::endl;
int j=0;
my_atoi(str,j);
std::cout << "j= " << j << std::endl;
return 0;
}
我想看看如何为他们获得生产质量代码 - 因为上面的性能并没有真正达到标准库的标准。
解决方案
推荐阅读
- java - 无法从 build.gradle 中的 System.getenv() 访问 mac 上的环境变量
- sql - 在 sql 中索引计算列表明它是不确定的并且失败
- javascript - 如何动态设置jquery ui对话框的左侧和顶部位置
- rxjs - rxjs:向可观察流动态添加值的最佳方法是什么?
- azure - 无 GUI 虚拟机中的 Azure CLI 非交互式登录
- html - 为什么 React 忽略样式表中的 h1 样式?
- mongodb - mongodb 3.2.7 排序不使用复合索引
- rust - 匹配结构中 () 和 {} 的区别
- javascript - 从 Javascript 中的变量中设置的 HTML 获取信息
- java - 原因:javafx.fxml.LoadException:Root 不是 javafx.scene.layout.AnchorPane 的实例