本文介绍了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中一个整数的位数之和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-28 03:50