7 kyu: Blowing Birthday Candles
這題很簡單,我在解這題時額外寫了一個簡單的函式,
後來發現用A and B or C的lua語法,就可以達成函式所做的事情,
這個語法,相當於C/C++裡的A ? B : C
也就是A的條件正確的話,回傳B,反則回傳C
用在Python 3的話,也相當於
B if A else C
B if A else C
完整程式碼如下:
local function blow_candles(str)
local a = 0
local i = 1
local s = {}
for i = 1, #str do
s[i] = tonumber(str:sub(i, i))
end
i = 1
while i <= #str do
local neg = s[i]
if neg > 0 then
for j = i, i+2 do
if j > #str then
break
else
s[j] = s[j] - neg > 0 and s[j] - neg or 0
end
end
a = a + neg
end
i = i + 1
end
return a
end
return blow_candles
沒有留言:
張貼留言