Excel精英培训网

 找回密码
 注册
数据透视表40+个常用小技巧,让你一次学会!
查看: 2768|回复: 3

[分享] [原创]任意长度正整数加法

[复制链接]
发表于 2009-10-7 17:23 | 显示全部楼层 |阅读模式

只考虑了正整数(速度还有很大的优化空间)

用的小学一年级的算法,嘿嘿

Function add$(a$, b$)
'任意长度正整数加法
Dim arrmax() As Byte, arrmin() As Byte
Dim la As Long, lb As Long, min As Long, max As Long
Dim iCF As Byte     '进位标志
Dim ret As Integer  '两个数相加的结果
Dim head As Byte
Dim temp As String

la = Len(a)
lb = Len(b)
If la > lb Then
    arrmax = a
    arrmin = b
Else
    arrmax = b
    arrmin = a
End If
head = UBound(arrmax) - UBound(arrmin)
For i = UBound(arrmax) - 1 To 0 Step -2
    If i >= head Then
        ret = arrmax(i) + arrmin(i - head) + iCF - 96
    Else
        ret = arrmax(i) + iCF - 48
    End If
    iCF = 0
    If ret >= 10 Then
        ret = ret - 10
        iCF = 1
    End If
    add$ = CStr(ret) & add$
Next
'最后一个iCF
If iCF = 1 Then add$ = "1" & add$
End Function
Sub test1()
'随机生成整数验证结果
Dim a$, b$
For i = 1 To 10
a = CStr(Int(10000 * Rnd()))
b = CStr(Int(10000 * Rnd()))
Debug.Print a + "+" + b + "=", add(a, b), CLng(a) + CLng(b)
Next
End Sub
Sub test2()
'随机生成任意长度整数
Dim nlen As Long
nlen = 30
Dim a$, b$
For i = 1 To Int(nlen * Rnd())
a = a + CStr(Int(10 * Rnd()))
Next
For i = 1 To Int(nlen * Rnd())
b = b + CStr(Int(10 * Rnd()))
Next
Debug.Print a + "+" + b + "=", add(a, b)
End Sub

发表于 2009-10-7 17:26 | 显示全部楼层
回复

使用道具 举报

 楼主| 发表于 2009-10-7 17:29 | 显示全部楼层
回复

使用道具 举报

 楼主| 发表于 2009-10-7 17:42 | 显示全部楼层

Function add$(a$, b$)
'任意长度整数加法
Dim arrmax() As Byte, arrmin() As Byte
Dim la As Long, lb As Long
Dim iCF As Byte     '进位标志
Dim head As Byte

la = Len(a)
lb = Len(b)
If la > lb Then
    arrmax = a
    arrmin = b
Else
    arrmax = b
    arrmin = a
End If
head = UBound(arrmax) - UBound(arrmin)
For i = UBound(arrmax) - 1 To 0 Step -2
    If i >= head Then
        arrmax(i) = arrmax(i) + arrmin(i - head) + iCF - 48
    Else
        arrmax(i) = arrmax(i) + iCF
    End If
    iCF = 0
    If arrmax(i) >= 58 Then
        arrmax(i) = arrmax(i) - 10
        iCF = 1
    End If
Next
add$ = arrmax

'最后一个iCF
If iCF = 1 Then add$ = "1" & add$
End Function

改进了一下,还可以改进减少循环次数,不过要用字符串函数,不知速度怎样

[em11][em11]
[此贴子已经被作者于2009-10-7 17:43:45编辑过]
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 注册

本版积分规则

小黑屋|手机版|Archiver|Excel精英培训 ( 豫ICP备11015029号 )

GMT+8, 2024-5-31 20:23 , Processed in 0.248347 second(s), 3 queries , Gzip On, Yac On.

Powered by Discuz! X3.4

Copyright © 2001-2020, Tencent Cloud.

快速回复 返回顶部 返回列表