5

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.

hjpotter92
  • 78,589
  • 36
  • 144
  • 183
Mikelong1994
  • 77
  • 2
  • 7

4 Answers4

6

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.

mpeterv
  • 463
  • 4
  • 11
  • +1. I don't know why people keep posting those 'convert it into a string and tostring each digit separately' methods; this is much more performant. – Colonel Thirty Two Mar 05 '14 at 23:47
4

Really a simple function. Using gmatch will get you where you need to go.

function sumdigits(str)
  local total = 0
  for digit in string.gmatch(str, "%d") do
  total = total + digit
  end
  return total
end

print(sumdigits(1234))

10

Basically, you're looping through the integers and pulling them out one by one to add them to the total. The "%d" means just one digit, so string.gmatch(str, "%d") says, "Match one digit each time". The "for" is the looping mechanism, so for every digit in the string, it will add to the total.

Josh
  • 3,225
  • 7
  • 30
  • 44
  • 3
    Use `%d` instead of `.`? – hjpotter92 Mar 04 '14 at 19:44
  • Doh! I knew I was missing something, haha. Thanks, hjpotter92! – Josh Mar 04 '14 at 19:44
  • 1
    You weren't missing anything. Just that `%d` would only select the digits. As long as `sumdigits` gets numerical inputs, your `.` would have worked as well. – hjpotter92 Mar 04 '14 at 19:46
  • Yeah, I just meant missing something as in "There's an easier way to get just digits, can't remember it." I would have probably found it much later, but now don't need to worry about it. – Josh Mar 04 '14 at 19:54
4

aSum = -load(('return'..a):gsub('%d','-%0'))()

Egor Skriptunoff
  • 23,359
  • 2
  • 34
  • 64
1

You might get better performance than gmatch (not verified) with:

function sumdigits(str)
  local total = 0
  for i=1,#str do 
     total = total + tonumber(string.sub(str, i,i))
  end
  return total
end
print(sumdigits('1234'))
10
Oliver
  • 27,510
  • 9
  • 72
  • 103