以下是Lua的实现:
function plus(str1, str2)
local increase = 0
local t = {}
local max = math.max(string.len(str1), string.len(str2))
for i = 0, max-1 do
local ch1 = string.sub(str1, -1 - i, -1 - i)
local ch2 = string.sub(str2, -1-i, -1-i)
if ch1 == "" then ch1 = "0" end
if ch2 == "" then ch2 = "0" end
local newv = increase + ch1 + ch2
increase = (newv - newv % 10) / 10
table.insert(t, newv%10)
end
if increase > 0 then
table.insert(t, increase)
end
local len = #t
local tmp
for i = 1, len/2 do
tmp = t[i]
t[i] = t[len-i+1]
t[len-i+1] = tmp
end
return table.concat(t)
end
function minus(m1, m2)
local borrow = 0
local t = {}
local max = math.max(string.len(m1), string.len(m2))
for i = 0, max-1 do
local ch1 = string.sub(m1, -1 -i, -1-i)
local ch2 = string.sub(m2, -1-i, -1-i)
if ch2 == "" then ch2 = '0' end
if ch1 - ch2 - borrow >= 0 then
table.insert(t, ch1-ch2-borrow)
borrow = 0
else
table.insert(t, ch1+10 - ch2 - borrow)
borrow = 1
end
end
repeat
if #t == 0 or t[#t] ~= 0 then
break
end
table.remove(t)
until #t == 0
local len = #t
local tmp
for i = 1, len/2 do
tmp = t[i]
t[i] = t[len-i+1]
t[len-i+1] = tmp
end
return table.concat(t)
end