遍历数字中的每个数字

问题描述:

我正在尝试创建一个程序,用于判断给定的数字是否为 Happy Number 或不。找到一个快乐的数字需要将数字中的每个数字平方,并将每个数字的平方结果加在一起。

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.

在Python中,你可以使用这样的东西:

In Python, you could use something like this:

SQUARE[d] for d in str(n)

但是我找不到如何在Java中迭代数字中的每个数字。正如你所知,我是新手,并且在Java文档中找不到答案。

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.

你可以使用模10运算得到最右边的数字,然后将数字除以10得到下一个数字。

You can use a modulo 10 operation to get the rightmost number and then divide the number by 10 to get the next number.

long addSquaresOfDigits(int number) {
    long result = 0;
    int tmp = 0;
    while(number > 0) {
        tmp = number % 10;
        result += tmp * tmp;
        number /= 10;
    }
    return result;
}

您也可以将其放入字符串并将其转换为char数组迭代它做类似 Math.pow(charArray [i] - '0',2.0);

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);