Sum of the digits of an integer in lua

有些话、适合烂在心里 提交于 2019-12-01 17:48:06

问题


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.


回答1:


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.




回答2:


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.




回答3:


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




回答4:


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


来源:https://stackoverflow.com/questions/22180828/sum-of-the-digits-of-an-integer-in-lua

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!