7 kyu: Dot Calculator
這題是用"."點的數目表示數字,並給operator做運算。
我的寫法是:
return function(equation)
local temp, s1, s2, op = 0, 0, 0, nil
for i = 1, #equation do
local c = equation:sub(i, i)
if '+' == c or '-' == c or '*' == c or '/' == c then
op = c
if temp > 0 then
s1 = temp
end
temp = 0
elseif '.' == c then
temp = temp + 1
end
end
s2 = temp
if '+' == op then
s2 = s1 + s2
elseif '-' == op then
s2 = s1 - s2
elseif '*' == op then
s2 = s1 * s2
elseif '/' == op then
s2 = s1 // s2
end
local s = ""
for i = 1, s2 do
s = s .. '.'
end
return s
end別人簡潔的寫法是:
return function(equation)
return ('.'):rep(load('return '..equation:gsub('%.+', string.len))())
end- This function compiles a chunk of Lua code from a string and returns it as a function. It does not execute the code immediately.
string.rep is a function in Lua's standard string library that repeats a given string a specified number of times.
沒有留言:
張貼留言