且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在C ++中附加一个整数(带整数)

更新时间:2023-11-10 14:14:46

首先乘以10乘以秒数的幂,再加上另一个。

Multiply first by ten to the power of digit number of second and add the other .

示例:63和5

63*10=630
630+5 =635

示例:75和34

75*100=7500
7500+34=7534
int i1=75;
int i2=34;
int dn=ceil(log10(i2+0.001));     //0.001 is for exact 10, exact 100, ...
int i3=i1*ceil(pow(10,dn)); <---- because pow would give 99.999999(for some optimization modes)
i3+=i2;

编辑:字符串版本需要2个int转换为str(这很慢) )和1字符串连接(不快)和1 str到int转换(慢)。上转换需要2个加法,1个对数,2个上限,1个幂,1个乘法,所有这些都可以在cpu中完成而不需要触及主内存来获取/设置子步骤的数据,这肯定比字符串版本的延迟更少。如果编译器设计将3-4个字符串存储在sse寄存器中,那么两者都将争夺性能。因为当一个人忙于计算功率功能时,其他人将忙于从sse中提取字符串并逐个放入必要的寄存器并通过开始加法和乘法构建在另一个寄存器上。功率(10,x)功能可以交易10 * 10 * 10 .... x次,因此纯数学版本再次变快。

String version needs 2 int to str conversion (which is slow) and 1 string concatenation (which is not fast) and 1 str to int conversion (which is slow). Upper conversion needs 2 additions, 1 logarithm, 2 ceilings, 1 power, 1 multiplication all of which could be done in cpu without touching main memory to get/set data for sub steps that is surely less latency then string versions. If 3-4 character strings are stored in sse registers by compiler design, then both would compete for performance. Because while one would be busy computing "power" function, other would be busy extracting string from sse and putting it necessary registers one by one and constructing on another register by starting additions and multiplications. Power(10,x) function can be traded for 10*10*10.... x times so pure math version becomes faster again.

如果它是可读性的你需要,eq-的回答是***的。

If it is readability you need, eq- 's answer is best imo.