迭代数字中的每个数字
我正在尝试创建一个程序,该程序可以判断给定的数字是否是“快乐数字”。要找到一个快乐的数字,需要对数字中的每个数字进行平方,然后将每个数字的平方的结果相加。
在Python中,你可以使用这样的东西:
SQUARE[d] for d in str(n)
但我找不到如何在Java中迭代数字中的每个数字。正如您所知,我是新手,在 Java 文档中找不到答案。
I am trying to create a program that will tell if a number given to it is a "Happy Number" or not. Finding a happy number requires each digit in the number to be squared, and the result of each digit's square to be added together.
In Python, you could use something like this:
SQUARE[d] for d in str(n)
But I can't find how to iterate through each digit in a number in Java. As you can tell, I am new to it, and can't find an answer in the Java docs.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
您可以使用模 10 运算来获取最右边的数字,然后将该数字除以 10 以获得下一个数字。
您还可以将其放入字符串中,然后将其转换为 char 数组,然后迭代它,执行类似 Math.pow(charArray[i] - '0', 2.0); 的操作
You can use a modulo 10 operation to get the rightmost number and then divide the number by 10 to get the next number.
You could also put it in a string and turn that into a char array and iterate through it doing something like
Math.pow(charArray[i] - '0', 2.0);
我想知道在 Java 中哪种方法能最快地将正数分解为数字,字符串 vs 模数
vs
通过传递
Long.MAX_VALUE
10,000,000 次来测试每个方法,字符串版本花费了 2.090 秒,模数版本花费了 2.090 秒版本 2.334 秒。 (在 Eclipse Neon 中运行的 64 位 Ubuntu 上的 Oracle Java 8)所以实际上并没有很多,但令我有点惊讶的是 String 更快
I wondered which method would be quickest to split up a positive number into its digits in Java, String vs modulo
vs
Testing each method by passing
Long.MAX_VALUE
10,000,000 times, the string version took 2.090 seconds and the modulo version 2.334 seconds. (Oracle Java 8 on 64bit Ubuntu running in Eclipse Neon)So not a lot in it really, but I was a bit surprised that String was faster
假设数字是一个整数:
Assuming the number is an integer to begin with:
在上面的例子中我们可以使用:
代替
In the above example we can use:
instead of
您可以将整数转换为字符串并迭代字符串中的每个字符。当你这样做时,将该字符转换为整数
You can turn the integer into a string and iterate through each char in the string. As you do that turn that char into an integer
此代码返回第一个符合您的描述的数字(1 之后)。
This code returns the first number (after 1) that fits your description.