lua中整数的位数之和 [英] Sum of the digits of an integer in lua

查看:1431
本文介绍了lua中整数的位数之和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看到了一个与Java和C相关的问题,但我使用的是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

如果你能解释我将如何在LUA中实现这一点以及代码为什么会这样做,那将非常感激。

If you could explain how I would achieve this in LUA and why the code does what it does, that would be greatly appreciated.

推荐答案

真的是一个简单的功能。使用gmatch可以获得你需要去的地方。

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

基本上,你是循环遍历整数并逐个拉出它们以将它们添加到总数中。 %d仅表示一位数,因此string.gmatch(str,%d)表示每次匹配一位。 for是循环机制,因此对于字符串中的每个数字,它将添加到总数中。

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.

这篇关于lua中整数的位数之和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆