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.
Method 1: Iterate through digits of a number in python using the iter() function. The first method to iterate through digits of a number is the use of iter() function. It accepts the string value as the argument. Therefore you have to first typecast the integer value and then pass it into it.
Iterables in Python are objects and containers that could be stepped through one item at a time, usually using a for ... in loop. Not all objects can be iterated, for example - we cannot iterate an integer, it is a singular value.
In this approach we will convert the integer into a string then we will traverse the string. Take the integer input. Convert the input into string data. Traverse through the string and print the character at each position that is the digits of the number.
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; }
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);
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); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With