Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sum of the digits of an integer in lua

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.

like image 688
Mikelong1994 Avatar asked Mar 04 '14 19:03

Mikelong1994


Video Answer


1 Answers

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.

like image 115
mpeterv Avatar answered Nov 04 '22 02:11

mpeterv