如何在C中连接两个整数

Stack Overflow已经用许多其他语言回答了这个问题,但不是C.所以我想我会问,因为我有同样的问题。

如何在C中连接两个整数?

例:

x = 11; y = 11; 

我想z如下:

 z = 1111; 

其他示例尝试使用字符串执行此操作。 没有字符串的方法是什么?

我正在寻找一种在C中执行此操作的有效方法,因为在我的特定用法中,这将成为代码的时间关键部分。

提前致谢!

 unsigned concatenate(unsigned x, unsigned y) { unsigned pow = 10; while(y >= pow) pow *= 10; return x * pow + y; } 

编译/正确/速度certificate

我避免使用log10pow函数,因为我很确定它们使用浮点并且速度很慢,所以在你的机器上这可能会更快。 也许。 轮廓。

 z = x * pow(10, log10(y)+1) + y; 

说明:

首先,您获得应该变为第二的变量的位数:

 int digits = log10(y)+1; // will be 2 in your example 

然后通过将其与10 ^位相乘来“移动”另一个变量。

 int shifted = x * pow(10, digits); // will be 1100 in your example 

最后添加第二个变量:

 z = shifted + y; // 1111 

或者在一行中:

 z = x * pow(10, (int)log10(y)+1) + y; 
 int myPow(int x, int p) { if (p == 0) return 1; if (p == 1) return x; int tmp = myPow(x, p/2); if (p%2 == 0) return tmp * tmp; else return x * tmp * tmp; } int power = log10(y); z = x*myPow(10,power+1)+y; 

在这里,我无耻地从https://stackoverflow.com/a/1505791/1194873复制了myPow

这可能不是一个最佳或快速的解决方案,但没有人提到它,它是一个简单的解决方案,可能是有用的。

你可以使用sprintf()strtol()

 char str[100]; int i=32, j=45; sprintf(str, "%d%d", i, j); int result=strtol(str, NULL, 10); 

首先用sprintf()写一个字符串,然后用另一个字符串写一个字符串(就像你用printf()打印到stdout一样),然后用strtol()将结果字符串转换为数字。

strtol()返回一个long ,它可能是一个大于int可以存储的值的值,因此您可能希望首先检查结果值。

 int result; long rv=strtol(str, NULL, 10); if(rv>INT_MAX || rv 

如果strtol()返回的值不在int的范围内(即,不在(包括) INT_MININT_MAX ),则发生错误。 INT_MININT_MAX来自limits.h

如果字符串中的值太大而无法在long表示,则errno将因溢出而设置为ERANGE (来自errno.h )。

在这里阅读strtol()

编辑:

正如chqrlie的启发性评论指出的那样,负数会给这种方法带来麻烦。

你可以使用这个或修改它来解决这个问题

 char str[100], temp[50]; int i=-32, j=45, result; sprintf(temp, "%+d", j); sprintf(str, "%d%s", i, temp+1); long rv=strtol(str, NULL, 10); 

首先将第二个数字与其符号一起打印到字符数组temp

+ %+d将导致打印数字的符号。

现在打印第一个数字和第二个数字到str但没有第二个数字的符号部分。 我们通过忽略temp的第一个字符来跳过第二个数字的符号部分。

最后strtol()完成了。

这是另一种方法:

 int concat(int x, int y) { int temp = y; while (y != 0) { x *= 10; y /= 10; } return x + temp; } 

谁知道你会得到什么样的表现。 试着看看..

也许这会奏效:

 int x=11,y=11,temp=0; int z=x; while(y>0) { // take reciprocal of y into temp temp=(temp*10)+(y%10); y=y/10; } while(temp>0) { // take each number from last of temp and add to last of z z=(z*10)+(temp%10); temp=temp/10; } 

代码很长,但很简单。 如果有任何错误,请纠正我。

这是@Mooing Duck的答案的变体,它使用10的倍数的查找表(对于具有慢整数乘法的平台)它还返回无符号long long以允许更大的值并在查找表中使用unsigned long long来解释@ chqrlie关于无限循环的评论。 如果可以保证组合输入不超过无符号,则可以更改这些输入。

 static const unsigned long long pow10s[] = { 10,100,1000,10000,100000,1000000,10000000,100000000,1000000000,10000000000 }; unsigned long long concat(unsigned x, unsigned y) { const unsigned long long *p = pow10s; while (y >= *p) ++p; return *p * x +y; } 
 #include using namespace std; int main() { int a=0,b=0,count=0,c=0,t=0; cout<<"enter 2 no"<>a>>b; t=b; while(b!=0) { b=b/10; count++; } while(count!=0) { a=a*10; count--; c=a+t; } cout<<"concate no is:"<