前两天去参加了一次华为的社会招聘会,面试官现场出了这样一道题:
请使用代码计算: 1234567891011121314151617181920*2019181716151413121110987654321 ,当时蒙了,求解啊?
------解决方案--------------------
结果=2492816912877266687794240983772975935013386905490061131076320
这是大数的乘法。
原理:
1、用字符串来存储大数
2、进行大数的乘法运算很简单.我这里说下我的运算方式.
3、方式:
a、首先移动大数的小数点(有的话)把大数扩展成一个正整数.
b、对大数按每9个字长来截取分别进行相乘(为什么会是9,因为2个9位数的正整数相乘结果不会超过多少位数,这个问题留着你思考,而这个乘的过程我们可以交给计算机的64位整数运算完成,例如VB.NET的Long类型)注意乘的过程移位的问题,即结果后是否需要添加多个0.
c、最后把所有截取的大数相乘的结果相加即可.
d、对于a把小数点移回去.
下面是VBNET源代码:(BigNumberMul)
Public Function BigNumberMul(ByVal Mul1 As String, ByVal Mul2 As String) As String '支持小数相乘。也支持负数
Dim mul11 As String = ""
Dim mul12 As String = ""
Dim mul21 As String = ""
Dim mul22 As String = ""
Dim t As Boolean = False
Dim i As Integer
Dim is2(1) As Boolean
If Mul1 = "" Or Mul2 = "" Or BigGetNumber(Mul1, mul11, mul12, is2(0)) = False Or BigGetNumber(Mul2, mul21, mul22, is2(1)) = False Then
Return ""
End If
i = mul12.Length - mul22.Length
If i > 0 Then
mul22 += StrDup(i, "0")
Else
mul12 += StrDup(-i, "0")
End If
i = mul22.Length * 2
mul11 = BigNumberMul_(mul11 + mul12, mul21 + mul22)
Dim j As Integer = i - mul11.Length + 1
If j > 0 Then
mul11 = StrDup(j, "0") + mul11
End If
If i > 0 Then
mul22 = Mid(mul11, mul11.Length - i + 1, i)
mul11 = Mid(mul11, 1, mul11.Length - i)
i = mul22.Length
While mul22.EndsWith("0")
i -= 1
mul22 = Mid(mul22, 1, i)
End While
If i > 0 Then
mul11 += "." + mul22
End If
End If
If is2(1) <> is2(0) Then
mul11 = "-" + mul11
End If
Return mul11
End Function
Public Function BigNumberMul_(ByVal Mul1 As String, ByVal Mul2 As String) As String '正整数相乘
Dim size1 As Integer = Mul1.Length
Dim size2 As Integer = Mul2.Length
Dim Mulret As String = ""
Dim i As Integer = size1 - size2
If i < 0 Then
Mulret = Mul1
Mul1 = Mul2
Mul2 = Mulret
i = size1