2016-03-06 118 views
1

我想将号码加入另一个号码而不是添加号码。如何在另一个号码的末尾添加号码

示例:代替1 + 1制作2,我想让它制作11

我想我唯一能做的事情就是+ 1,但只是使它2,我想它,使其11

+4

你甚至在问什么? –

回答

5

如果我理解你的要求,你要这样:

1 + 1 = 11 

不是:

1 + 1 = 2 

要做到这一点,只投了数字串和将它们连接起来。然后,您可以将结果转换回数字。

string result = 1.ToString() + 1.ToString(); // or, "1" + "1" 
result == "11"; 
int numberResult = Convert.ToInt32(result); 
2

如果您需要将其多次添加在你的代码,它能够更好地创造这样的功能:

public static int JoinNumber(int x, int y) 
{ 
    int z = 0; 
    string temp = Convert.ToString(x) + Convert.ToString(y); 
    z = Convert.ToInt32(temp); 
    return z; 
} 

public static int JoinNumber(int x, int y) 
{ 
    return Convert.ToInt32(Convert.ToString(x) + Convert.ToString(y)); 
} 

您需要创建长期过载和其他类型根据您的要求。

3

您可以通过使用指数和对数避免串实例化和转换:

public static int Concat(int x, int y) 
{ 
    return x * (int)Math.Pow(10, Math.Floor(Math.Log(y, 10)) + 1) + y; 
} 

此作品由10的幂有一样多的零作为y具有数字乘以x,那么就总结y到它。在数学上:X×10 ⌊log ý⌋+ 1 + ÿ

这将导致一个结果,两个数字的小数表示看起来已经连接在一起。 例如:

Concat(1, 1)  : 1 *  10 +  1 
Concat(3, 54)  : 3 * 100 + 54 
Concat(28, 999) : 28 * 1000 + 999 
Concat(76, 84215) : 76 * 100000 + 84215 

如果你知道你的号码通常是小,你可以写热路径,以避免计算昂贵PowLog操作:

public static int Concat(int x, int y) 
{ 
    if (y < 10)  return x * 10 + y; 
    if (y < 100) return x * 100 + y; 
    if (y < 1000) return x * 1000 + y; 
    if (y < 10000) return x * 10000 + y; 

    return x * (int)Math.Pow(10, Math.Floor(Math.Log(y, 10)) + 1) + y; 
} 
+0

我的意思是......你没有错。 – Steve

1

所有你想要的是:

string result = String.Concat(1, 1); 

真的,就是这样。

如果你想回去的整数值的模糊的原因:

int result = Int32.Parse(String.Concat(1, 1)); 

提防溢出。