遍历数字中的每个数字 [英] Iterate through each digit in a number

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

问题描述

我正在尝试创建一个程序,用于判断给定的数字是否为 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);

这篇关于遍历数字中的每个数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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