Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterate through each digit in a number

Tags:

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.

like image 548
Isaac Lewis Avatar asked Feb 15 '11 21:02

Isaac Lewis


People also ask

How do you iterate through a digit in a number in python?

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.

Can you iterate through integer?

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.

How do you traverse a number in Java?

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.


2 Answers

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

like image 76
Argote Avatar answered Nov 15 '22 14:11

Argote


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); } 
like image 39
yavoh Avatar answered Nov 15 '22 14:11

yavoh