I saw a question like this relating to Java and C, but I am using LUA. The answers might have applied to me, but I wasn't understanding them.
Could someone please tell me how I would get the sum of the individual digits of an Integer. For Example.
a = 275
aSum = 2+7+5
If you could explain how I would achieve this in LUA and why the code does what it does, that would be greatly appreciated.
You can use this function:
function sumdigits(n)
local sum = 0
while n > 0 do
sum = sum + n%10
n = math.floor(n/10)
end
return sum
end
On each iteration it adds the last digit of n to the sum and then cuts it from n, until it sums all the digits.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With