Alex Rivera | Logout

Iterate through each digit in a number

Asked 2011-02-15T21:15:47.800
26

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.

Edit
Report

1 Answer

8

Assuming the number is an integer to begin with:

int num = 56;
String strNum = "" + num;
int strLength = strNum.length();
int sum = 0;

for (int i = 0; i < strLength; ++i) {
  int digit = Integer.parseInt(strNum.charAt(i));
  sum += (digit * digit);
}
answered 2011-02-15T21:20:13.243

Your Answer