大数big number的加减运算
2016-11-25 14:37
357 查看
以下是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
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
相关文章推荐
- Big Number-大数运算
- 支持无限精度无限大数的类BigNumber实现
- 大数运算之加减乘法
- java中进行高精度、大数运算总结BigInteger BigDecimal
- 大数BigInteger精确数Decimal的运算操作
- java大数算法完成五则运算之加减
- 求大数阶乘的位数(ACM Big Number问题)
- c++实现大数的加减乘运算(数组存放)
- Java中两个大数之间的相关运算及BigInteger代码示例
- C# 4.0 大数的运算--BigInteger的应用详解
- hdu1212 Big Number &第六届山东省赛Single Round Math (同余定理,大数取模)
- 【原】biginteger。大数乘法。大数运算。“无限大数字”乘法。大数乘法两种方法对比
- hdu1212 Big Number &第六届山东省赛Single Round Math (同余定理,大数取模)
- 九度+大数运算+Java直接调用BigInteger,注意必须定义的是Main类OJ才过
- 用汇编实现大数的加减运算
- BigNumberPlus大数加法
- 大数加法 big number add
- 要求实现方法public String addTwoBigNumber(String s1,string s2) 大数相加,注意处理异常
- HDU1212:Big Number(大数求模)
- hdoj1212(大数取余)Big Number